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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With