Overriding

The ability to define behaviour that’s specific to a particular subclass type. It means a method is implemented in superclass and subclass has some specific behaviour so subclass is free to implement the same method again.  This concept is called as overriding.

Important Points
  • Inheritance is required to achieve Overriding.
  • Overriding is runtime polymorphism.

 The Rules for overriding a method

  • Subclass -> overriding method -> must have exactly same argument list.
  • Subclass -> overriding method -> must have exactly same return type.
  • Subclass -> overriding method -> must not be restrictive than overridden method.
  • Subclass -> overriding method -> must not throw newer or broader checked exception.
  • Final methods can’t be overridden.

    Some key points for above demo:
1) Class Jungle is inheriting class Technical. SubClass and SuperClass, both have same method (named display()).
2) Object is getting created for class Technical. So at runtime method display() of class ‘Technical’ is getting called.
Technical object1 = new Technical();object1.display();
Some key points for above demo:
  1.   Class ‘JungleTech’ is having ‘display()’ overridden method.
  2.    Check below code:
    Technical object1 = new JungleTech();object1.display();—- Left side of object1 is class ‘Technical’, it means ‘Technical’ is super class and it can hold base class object. In this code object is getting created for JungleTech class.—- If super class, left side, does not have display method then ‘object1.display();’ will give compile time error. The reason is at compile it JVM will check whether display method is available in super class (Technical) or not. See the demo below.

    Final methods can’t be overridden

     Subclass -> overriding method -> must not be restrictive than overridden method.

 

If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.