Monday 14 October 2013

Why overridden methods cannot have more strict access modifier?


 You must have come across a lot of examples in which access modifier of overridden method is less strict. For example is access modifier of a method is private than the overriding method in the subclass can have access modifier defualt(no modifier), protected or private.


One commonly used example is the protected Object clone() method from java.lang.Object class. It is generally overridden as public Object clone().

Most obvious question to follow is why such a behavior?


The answer lies in the question itself. Try to answer a counter question what happens if more strict access modifier is allowed for the overridden method?

Lets take a simple example to identify the problem. Lets say we have two classes Animal and Dog as follows -  

Class Animal :

package animalsData;

public class Animal {
    public void run() {
        System.out.println("Running");
    }
}


Class Dog : 

package animalsData;

public class Dog extends Animal {   
    private void run()
    {
        System.out.println("Dog is running");
    }
}


If  you are using an IDE(Eclipse,Netbeans etc) you will directly see the error. If you are using command line or a simple text editor(gedit, notepad etc) try compiling above code. You will get the following error -



Lets analyze the potential problem in above scenario. Try executing following piece of code

    public static void main(String args[]) {
        Animal animal = new Dog();
        animal.run();
    }


At compile time all java compiler does is see the reference type of the object(Animal in our case) and check whether the method called is available(declared or defined) class of reference type(In our case run() method is present in the Animal class which is the reference type). So there would be no errors in compilation but what happens when we run our code. Runtime class of the object is Dog and the corresponding run() method of Dog class will be invoked(Refer how function overriding is a runtime phenomenon ). But as per the access modifiers private methods must be called from the class only(not by it's instances). As this scenario violates basic principles laid down by java language it is not allowed.

On the other hand access modifier of the overriding method can be relaxed because it makes sense. In our example above if run() method in Animal class was private and that in Dog class was public we could easily execute our main code.[Keeping into consideration access modifier restrictions]
t> UA-39527780-1 back to top