Method overriding means have same signature but with different implementation. It occurs when a class declares a method that has the same type signature as a method declared by one of its superclasses.
Signature is a combination of a method name and the sequence of its parameter types.
When a method in the subclass overrides a method in a superclass, the method in the superclass is hidden relative to the subclass object.
Note that Method Overriding is a very important feature of java because it forms the basis for run-time polymorphism.
Superclass reference can be used to refer to a subclass object. The dynamic method dispatch mechanism in java selects the appropriate version of an overridden method to execute based on the class of the executing object, not the type of a variable that references that object.
The actual version of an overridden method that is executed is determined at run-time, not compile time.
Syntax of Method Overriding
class clsName1
{
// methods
rtype1 mthName(cparam1)
{
// body of method
}
}
class clsName2 extends clsName1
{
// methods
rtype1 mthName(cparam1)
{
// body of method
}
}
Example of Method overriding
Example 1 : Program that illustrates how to override mehods and also shows which method will be called run time based on object assigned to class variable
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move()
{
System.out.println("Dogs can walk and run");
}
}
class MethodOverridingDemo
{
public static void main(String args[])
{
Animal aObj1 = new Animal();
Dog dObj = new Dog();
Animal aObj2 = new Dog();
aObj1.move();
dObj.move();
aObj2.move(); // Dynamic method dispatch
}
}
Output
Animals can move
Dogs can walk and run
Dogs can walk and run