Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Method inheritance and use of Super keyword to access superclass method

Posted By: Balbir Kaur     Category: Java     Views: 11083

This article explains about due to method overriding how to access superclass method in java using example.

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

  

  

  
Share: 



Balbir  Kaur
Balbir Kaur author of Method inheritance and use of Super keyword to access superclass method is from Singapore.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!