如何判断子类继承的是所有还是非私有?
我想的方法是:
如果子类没有继承到私有方法,那当子类调用父类私有方法时,运行程序应该会报错未定义方法;
如果子类继承了父类所有方法,那当子类调用父类私有方法时,运行程序应该会报错方法不可见或者无权限。
示例的代码(报错:):
class TestF {
private void aaa() {
System.out.println(1);
}
}
class TestS extends TestF {
}
public class Test {
public static void main(String[] args) {
TestS test = new TestS();
test.aaa();
}
}
IDEA报错(英文):'aaa()' has private access in 'test.demo.TestF'
IDEA中文报错:'aaa()' 在 'test.demo.TestF' 中具有 private 访问权限
eclipse报错:The method aaa() from the type TestF is not visible
之后我把private的那行注释掉:
class TestF {
// private void aaa() {
// System.out.println(1);
// }
}
class TestS extends TestF {
}
public class Test {
public static void main(String[] args) {
TestS test = new TestS();
test.aaa();
}
}
IDEA报错(英文):Cannot resolve method 'aaa' in 'TestS'
IDEA中文报错:无法解析 'TestS' 中的方法 'aaa'
eclipse报错:The method aaa() is undefined for the type TestS
最后我的结论是:Java中,子类继承时是继承父类的所有方法
《疯狂Java讲义》ISBN 9787121066467 第144页:
2023.4.19更新:
发现有位大佬用反射来证明(今天刚想到这个就发现已经证过了)