use*_*135 4 java private public access-modifiers
有人可以演示一个简单程序的示例,其中在工作程序中将一个方法的访问权限从私有更改为公共将不会导致编译错误,但只会导致程序行为不同吗?
此外,何时添加新的私有方法会导致编译错误或导致程序行为不同?
这与继承发挥作用.子类可以具有与其父类中的私有方法具有相同签名的方法,但不能覆盖它.
public class Scratchpad {
public static void main(String[] args) {
new Sub().doSomething();
}
}
class Super {
public void doSomething() {
System.out.println(computeOutput());
}
private String computeOutput() {
return "Foo";
}
}
class Sub extends Super {
public String computeOutput() {
return "Bar";
}
}
Run Code Online (Sandbox Code Playgroud)
如果按原样运行,你就会得到Foo.如果你改变Super#computeOutput()对public,你得到Bar.那是因为Sub#computeOutput()现在会覆盖Super#computeOutput().