关于JAVA访问控制符的问题
来源:百度知道 编辑:UC知道 时间:2024/06/01 12:25:33
protected:只有在不同包的非子类下不可见。
为什么test2里看不见test1里的protected属性和方法。
import com.dg.test.base.control.a.Test1;
public class Test2 extends Test1 {
public static void main(String[] args) {
Test1 test = new Test1();
String s1 = test.testprotected;
String s2 = test.testpublic;
test.testprotected();
test.testpublic();
}
}
------------------------------------------------------
public class Test1 {
String testdefault;
public String testpublic;
private String testprivate;
protected String testprotected;
void testdefault() {
}
protected void testprotected() {
}
private void testprivate() {
}
public void testpublic() {
}
}
为什么报错说:The method testprotected() from the type Test1 is not visible
把test2里的 Test1 test = new Test1();改为 Test2 test = n
为什么test2里看不见test1里的protected属性和方法。
import com.dg.test.base.control.a.Test1;
public class Test2 extends Test1 {
public static void main(String[] args) {
Test1 test = new Test1();
String s1 = test.testprotected;
String s2 = test.testpublic;
test.testprotected();
test.testpublic();
}
}
------------------------------------------------------
public class Test1 {
String testdefault;
public String testpublic;
private String testprivate;
protected String testprotected;
void testdefault() {
}
protected void testprotected() {
}
private void testprivate() {
}
public void testpublic() {
}
}
为什么报错说:The method testprotected() from the type Test1 is not visible
把test2里的 Test1 test = new Test1();改为 Test2 test = n
你好
protected的访问权限是对同一包中的类和非同一包中的子类可访问
也就是说对非同一包中的非子类不可见
这当然也包括父类本身
所以在不同包中父类也不能访问自己的protected方法
你 Test1是父类 所以在不同包中看不到自己的protected 方法
而Test2是子类 就看的到了
题外话
这就是为什么不能用Object对象本身直接调用initial()和clone()方法的原因
他们为protected的
希望回答你还满意~
protected 属性是私有的
test2 无法访问 test1的私有方法和变量
你可以将他们设为public的
protected 表明被它修饰的成员变量为保护类型,在同一个包里和 public 类型是一样的,也是能够访问到的。但是如果在不同包里的 protected 类型的成员变量就只能通过子类来访问。
Test2 test = new Test2(); 你新建了一个Test2,在虽然test的变量是包中私有的,但调用他的类本身就是同一种类,当然属于同一包,能够访问它的变量!
Test1 实例化的 test 与Test2类不属于同一包