OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 16 : Method Overriding in Java
Unit - 2
Topic - 16: Method Overriding in Java
Definition
In a class hierarchy, when a method in a subclass has the same name and same type signature as a method in its superclass, the method in the subclass overrides the one in the superclass.
Key Points
-
When an overridden method is called from a subclass object, it will always execute the subclass version.
-
The superclass version is hidden.
-
First, Java checks if the method exists in the superclass.
-
If yes, it executes the subclass version.
-
If no, it throws a "method not found" error.
-
-
Methods with different signatures are overloaded, not overridden.
Example Program
Output
Dynamic Method Dispatch in Java
Definition
Dynamic Method Dispatch is a mechanism by which a call to an overridden method is resolved at runtime rather than compile time.
It enables runtime polymorphism in Java.
Before You Begin
We must understand the concept of superclass reference and subclass object:
-
A reference variable of a superclass can refer to an object of its subclass.
-
Which version of the overridden method gets called is decided at runtime, based on the actual object being referred to.
Example Program
Output
Explanation
-
The reference
r
is of type A, but it can refer to objects of A, B, or C. -
The actual method execution depends on the object type that
r
refers to at runtime. -
This behavior is the foundation of polymorphism in Java.
Comments
Post a Comment