bra*_*orm 4 java methods inheritance constructor access-modifiers
在下面的代码中,构造函数的Child可见性降低public了private,这是允许的.继承的方法(例如)test()不能降低可见性.为什么Java以这种方式运行?
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!");
}
}
Run Code Online (Sandbox Code Playgroud)
rge*_*man 13
构造函数不是继承的,因此Child()不会覆盖Parent().
至于方法,如果您有(如果Child()是public)
Parent p = new Child();
p.test();
Run Code Online (Sandbox Code Playgroud)
如果它被允许,这将调用一个private方法.因此,不允许在覆盖时缩小访问范围.