Wednesday, 4 November 2015

Rules of method overriding in java : The Pictorial Way

In the previous post we have seen what is method overriding and how we can access overridden methods. In this post we will cover what are the rules to override a particular method from superclass to subclass.

#Rule 1 : Argument list must exactly match


#Rule 2 : Return type should be same as of supper class method or it can be a covariant return type.

What is covariant return type?
Subtype of original return type is known as covariant return type

#Rule 3 : Access level cannot be more restrictive


Why derived class overriding method should not be more restrictive than base class method in java?
Suppose someone access Animal class and thinks eat() is a public method and so it is safe to use this method with Animal class reference, and if at runtime JVM binds Animal reference with Horse object and Horse object have eat() as private method about which the person who is accessing Animal class eat() is completely unaware, than program will crash so derived class overriding method should not be more restrictive than base class.


#Rule 4 : Overriding method cannot throw new or broader checked exceptions


Why derived class overriding method should not throw broader exception than base class?
The reason behind this is same as above explanation, if derived class throws broader exception and JVM binds the base class reference with derived class object, than the code, which is accessing base class method, will fail. 


#Rule 5 : You cannot override final and static method
Why static method cannot be overridden in subclass in java ?
This is because at run time while accessing the static method compiler will replace the instance with class name, and so it will always access the method to which reference is pointing and not to which object is pointing.
However though you cannot override a static method in subclass, you can always redline static method in subclass.







1 comment:

  1. Nice one, you explain things in a very simple way. Keep it up.

    ReplyDelete