Sunday 1 November 2015

What is method overriding in java with example : The Pictorial Way

Overriding Method 

I have explained how to override a method in below image.

As I said, I like to explain things in pictorial way, which is compact and easy way to understand, so you will find very less text in my posts, but if at some point you don't understand any concept you can always ask question and I will be happy to help you.

In below diagram you will get answer to following questions.

  • What is Overriding in java with example? 
  • How to access overridden methods in java?

What is overridden method in java ? 
A method in subclass is called overridden method if it satisfies below conditions
  • Same method name as of in Super class
  • Same or broader access specifier
  • Same return type or covariant return type (I will explain covariant return type in next post)
  • Exactly same argument list.
Accessing overridden method in java :
As you can observe in image, no matter what is the reference type, Java will always consider the object to which the reference is pointing.

Why object type and not reference type determines which overridden method to invoke ?
This is because overriding method is a type of run time polymorphism, by this I mean the method binding is done at run time depending upon the object being referred  at that point of time.


How to invoke super class version of overridden method?
To invoke super class version you can use "super" keyword.
Suppose in our above example if you want to invoke first eat method of Animal class and than you want to continue with eat method of horse class; in this scenario you can change eat method of Horse class in following way.

public void eat()
{
super.eat();
//followed by Horse specific functionality

}

When to use overriding method?
Overriding is useful in following scenarios
  • If you want to add some functionality to the method existing in super class.
  • If you want to suppress the functionality of the method present in super class.


In the next post I will explain all the rules to override a method in java.


3 comments:

  1. Nice article, it helps me in understanding very easily pictorial way. Required some more post on java concepts.

    ReplyDelete
    Replies
    1. Hi, Thanks for your comment, let me know the topics you want to be explained in pictorial way.

      Delete
  2. It is very helpful to understand overriding as pictorial way.It will helpful if you write about java collections.. HashSet, HashMap, Tree... etc. Thank you again.

    ReplyDelete