Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Why derived class overriding method should not be more restrictive than base class in java.Why compiler throws error?can you please anyone explain reason for that?

like image 700
Rose Avatar asked Apr 24 '13 06:04

Rose


People also ask

Why overridden method should not be more restrictive?

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.

Can we restrict visibility of derived method in Java?

You cannot reduce the visibility of a inherited method. Here parent class has func() method which is public and overridden by the subclass TestClass which is private.

Why would override a method of a base class?

An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override. Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden.


2 Answers

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.

like image 50
Jon Skeet Avatar answered Oct 02 '22 01:10

Jon Skeet


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.

like image 39
Jaydeep Rajput Avatar answered Oct 02 '22 01:10

Jaydeep Rajput