我有以下两个类(class): 测试.java
package com.test.app;
public class Test {
public int a=10;
protected void testFunc() {
// TODO Auto-generated method stub
System.out.println("Test class--> testFunc");
}
}
另外一个是 主程序.java 包 com.test.main;
import com.test.app.Test;
public class Main extends Test {
public static void main(String[] argv) {
System.out.println("Main Method");
Main main =new Main();
main.testFunc(); // No Error
Test test = new Test();
test.testFunc(); // Error
}
}
类型 Test 中的方法 test.testFunc() 不可见
最佳答案
Test#testFunc()
方法只能由子类(如 Main
)和同一包中的类(com.test.应用程序
)。
这就是为什么声明
main.testFunc();
编译正常(因为Main
是Test
的子类,并且允许调用testFunc()
)。
但是这个声明
test.testFunc();
无法编译,因为Main
类所在的包不是com.test.app
,而是com.test.main
.
更多信息:
关于Java:当我使用extends关键字实现多重继承时,在不同包的不同类中无法访问 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36568941/