Why derived class overriding method should not be more restrictive than base class in java?

The point is that a caller who only knows about your superclass should still be able to use any instance of the subclass that it's given. Consider this situation:

public class Super
{
    public void print()
    {
        System.out.println("Hello!");
    }
}

public class Sub extends Super
{
    @Override
    void print() // Invalid
    {
        System.out.println("Package access");
    }
}

Now from a different package, imagine we had:

public void printSuper(Super x)
{
    x.print();
}

and we called that with:

printSuper(new Sub());

What would you expect that to do? You're overriding the method, so it should print "package access" - but then that means you're calling a package access method from a different package...

Basically, this is just one example of the Liskov Substitution Principle in action. You should be able to treat any instance of a subclass as an instance of the superclass, and it's hard to see how that fits in with making things more restrictive in a subclass.


You can not make access modifier more restrictive, because that would violate the basic rule of inheritance that a subclass instance should be replacable in place of a superclass instance.

For e.g Suppose that Person class has getName public method which is being used by many classes(including non-sub classes).But somebody just added Employee as subclass of Person and getName in Employee is protected which should be accessed only by sub-classes then the previous code would start breaking and Employee would not be replacable to Person object.

Hence java has decided to impose this restrcition.

Tags:

Java