关于protected修饰符的用法
子类与基类不在同一包中,那么在子类中,子类实例可以访问其从基类继承而来的protected方法,而不能访问基类实例的protected方法
//示例一
package p1;
public class Father1 {
protected void f() {} // 父类Father1中的protected方法
}
package p1;
public class Son1 extends Father1 {}
package p11;
public class Son11 extends Father1{}
package p1;
public class Test1 {
public static void main(String[] args) {
Son1 son1 = new Son1();
son1.f(); // Compile OK ----(1)
son1.clone(); // Compile Error ----(2)
Son11 son = new Son11();
son11.f(); // Compile OK ----(3)
son11.clone(); // Compile Error ----(4)
}
}
f方法来自于Father1,Father1与调用所在类Test1同包,可以访问。clone方法来自Object,子类中可以通过子类实例访问clone,但是Test1不属于Son1及Son11继承链上Object的子类
//示例二
package p2;
public class MyObject2 {
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
package p22;
public class Test2 extends MyObject2 {
public static void main(String args[]) throws CloneNotSupportedException {
MyObject2 obj = new MyObject2();
obj.clone(); // Compile Error ----(1)
Test2 tobj = new Test2();
tobj.clone(); // Complie OK ----(2)
}
}
clone方法来自MyObject2,子类中可以通过MyObject2的子类实例访问clone方法,(1)不通过,(2)通过
//示例三
package p3;
public class MyObject3 extends Test3 {
}
package p33;
public class Test3 {
public static void main(String args[]) throws CloneNotSupportedException {
MyObject3 obj = new MyObject3();
obj.clone(); // Compile OK ------(1)
}
}
clone方法来自Object,Test3是继承链上Object的子类,可以通过子类MyObject3的实例访问clone(继承链MyObject3>Test3>Object)
//示例四
package p4;
public class MyObject4 extends Test4 {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package p44;
public class Test4 {
public static void main(String args[]) {
MyObject4 obj = new MyObject4();
obj.clone(); // Compile Error -----(1)
}
}
clone方法来自MyObject4,继承链(MyObject4>Test4>Object),Test4不是MyObject4的子类
//示例五
package p5;
public class MyObject5 {
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
public class Test5 {
public static void main(String[] args) throws CloneNotSupportedException {
MyObject5 obj = new MyObject5();
obj.clone(); // Compile OK ----(1)
}
}
clone方法来自MyObject5,并且Test5与MyObject5同,可见
//示例六
package p6;
public class MyObject6 extends Test6{}
public class Test6 {
public static void main(String[] args) throws CloneNotSupportedException {
MyObject6 obj = new MyObject6();
obj.clone(); // Compile OK -------(1)
}
}
clone来自Object,继承链(MyObject6>Test6>Object),Test6是Object的子类,它的子类实例MyObject6可以访问clone
//示例七
package p7;
public class MyObject7 extends Test7 {
public static void main(String[] args) {
Test7 test = new Test7();
test.clone(); // Compile Error ----- (1)
}
}
public class Test7 {
}
clone来自Object,继承链(MyObject7>Test7>Object),不能在MyObject7中实例化父类Test7的成员来访问clone