Google+

110. Method Overriding






In a class hierarchy, when a method in a subclass has the same name and type as a method in superclass, then the method in the subclass is said to override the method in superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. In order to call the hidden/overridden method of the superclass we've to use the syntax:  super.methodname( ); 

We have already implemented 'Method  Overriding' in our previous post #104 Using super keyword to access the methods of 'superclass'

What if the name of the method in superclass is same as the method in subclass but type of the methods is not same. Will the method still gets overridden?
No. The method will get overloaded instead. You can call both the methods with a change in type without using 'super' keyword. Please find the following example:

Method with same name in superclass and has single parameter as type:

sample(int a)
{
      System.out.println("The value of instance variable a is "+a);
}

Method with same name in subclass but has different type i.e. has two parameters:

sample(int a, int b)
{
    System.out.println("The sum of a and b is " + (a+b));
}

Now if you call the methods using the following call statements from the subclass:

  • sample(10) -> It will call the method in the superclass as it has only one parameter
  • sample(10,10) -> It will call the method in the subclass as it has two parameters

When the methods in the super and subclass have same name but different type/parameters, then we can say that method in the subclass is overloading the method in the superclass.

When the methods in the super and subclass have same name and same type/parameters, then we can say that method in the subclass is overriding the method in the superclass and we have to use 'super' keyword to access the method in the superclass.




Please comment below to feedback or ask questions.

'Dynamic Method Dispatch' will be explained in the next post.



No comments:

Blog Index