Thursday, 19 July 2012

Rules for Overriding Methods in Java

Rule 1) A method is said to be overriden if a class which extends another class defines method with the same name and arguments list.

Rule 2) The method defined in the base class should be visible in the derived class. If this is not so, the method in the derived class will not be considered overridden version but will be treated as a normal method.

Rule 3) The method name and arguments list should be same for overriding and overridden methods. But the return type can be co-variant. This means that if the return type of the method in super class is
Map, then the return type of the same method can be HashMap.

Rule 4) The access specifier in the overriding method (in the derived class) should not be more limiting than that of the overriden method (in the base class). This means that if the access specifier for base class method is protected then the access specifier for the derived class method should not be default or private but can be protected, public. The order of increasing visibility of various specifiers is:

private, default, protected, public

Rule 5) The exceptions specified in the derived class method should be either same or sub-class of them. Thus if the base class method specifies the exception as IOException in the throws clause then the derived class method can specify the exception as FileNotFoundException, IOException but not Exception.

Tips for Overriding Methods in Java

Tip 1) Choose to override when the base class/interface version is generic in nature.
Tip 2) Use inheritance and overriding of methods judiciously as it increases coupling between classes.
Tip 3) Try to invoke overridden methods by creating a reference of base class/interface type and making it refer to the derived class object. This helps in coding to generalization and helps creating lesser number of references.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...