Monday 5 October 2015

Java Method Overriding Rules


1) The method argument list in overridden and overriding methods must be exactly same if they don’t match, you will end up with an overloaded method.

Method overriding exists only in sub class.

2) The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.

3) private, static and final methods cannot be overridden.

4) An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not.

5) Overriding method cannot throw checked Exception higher in hierarchy than thrown by overridden method.

Example: parent class method throws FileNotFoundException, the overriding child class method can throw FileNotFoundException; but it is not allowed to throw IOException or Exception, because IOException or Exception are higher in hierarchy i.e. super classes of FileNotFoundException.

5) Overriding method cannot reduce the access scope of overridden method.

If overridden method in parent class is protected, then overriding method in child class cannot be private. It must be either protected (same access) or public (wider access).

6) A subclass in a different package can override the methods declared public or protected and default can override in same package.

7) Constructors cannot be overridden.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...