Overriding Tutorial

Rule for overriding:

1) In overriding method signature must be matched in both super and sub class.

2) Co-variant return type: Child class method return type should need not be same as super class method return type. Its child classes are allowed.

Example:

This is valid from java 1.5

Co-variant return type rule is only for objects. Not for primitives.

3) final methods of super class cannot be override in sub class.

4) private methods are visible to only to the declared class. So no overriding for private methods. If you define same in sub class, then it acts as normal method but not overriding.

5) It’s possible to override super class non-abstract method as abstract method in sub class to stop parent class method implementation availability to the sub class

6) In overriding, you can increase the scope of return type but you cannot decrease the scope.

 

7) If sub class is throwing checked exception then super class should throw the same checked exception or its super class exception.

Examples:

 

8) Static method cannot be override as non-static and non-static method cannot be override as static.

9) There is no concept of static method overloading. If both super and sub class methods have same method declaration with static , then it is called Method Hiding.

OUT PUT

If you remove static from both super and sub class methods in above example ,then output will be as below

 

10)  It’s not possible to override var-arg method with normal method. If we override then it becomes overloading but not overriding.

Var-arg method should be overridden with var-arg method only.

Example:

OUT PUT

If super and sub class methods have var-arg methods then it will become overriding. Output will be

 

Posted in java and tagged , .

2 Comments

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">