The dynamic dispatch mechanism in java automatically selects the correct version of a method for execution based upon the type of object being referred to at the time the method is executed. But this creates one problem if you want to access the functionality present in the superclass version of an overridden method.
To overcome from this problem java provides one mechanism. To access a superclass method use super keyword.
Syntax to call overridden method of superclass in overridden method of subclass
super.mthName(args)
mthname is a name of the superclass method and args is an optional argument list.
Example to call overridden method of superclass in overridden method of subclass
Example 1 : Program that illustrates how to call overridden method of superclass in overridden method of subclass
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move()
{
super.move();
System.out.println("Dogs can walk and run");
}
}
class SuperWithMethodDemo
{
public static void main(String args[])
{
Animal aObj1 = new Animal();
Dog dObj = new Dog();
Animal aObj2 = new Dog();
aObj1.move();
System.out.println("");
dObj.move();
System.out.println("");
aObj2.move(); // Dynamic method dispatch
}
}
Output
Animals can move
Animals can move
Dogs can walk and run
Animals can move
Dogs can walk and run