In the following code, the constructor of Child
has reduced visibility from public
to private
, which is allowed. The inherited methods, such as test()
, cannot have reduced visibility. Why does Java operate this way?
class Parent {
public Parent(){}
public void test()
{
System.out.print("parent test executed!");
}
}
class Child extends Parent{
private Child(){}
private void test(){
System.out.print("child test executed!");
}
}
Constructors are not inherited, so Child()
doesn't override Parent()
.
As for the methods, if you have (if Child()
were public
)
Parent p = new Child();
p.test();
Had it been allowed, this would be invoking a private
method. So narrowing the access while overriding is not permitted.
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