您的位置:首页 > 编程语言 > Java开发

谈谈JAVA中的protected访问权限

2008-10-03 11:55 357 查看
privatedefaultprotectedpublic
同类TTTT
子类(同一包中)FTTT
类(同一包中)FTTT
子类(不同包中)FFT/FT
类(不同包中)FFFT
关于在子类不同包中时protected的访问权限的问题
protected access requires a little more elaboration. Suppose class A declares a protected field x and is extended by a class B, which is defined in a different package (this last point is important). Class B inherits the protected field x, and its code can access that field in the current instance of B or in any other instances of B that the code can refer to. This does not mean, however, that the code of class B can start reading the protected fields of arbitrary instances of A! If an object is an instance of A but is not an instance of B, its fields are obviously not inherited by B, and the code of class B cannot read them.[java in a nutshell]
下面一个例子转载自Blog: http://zhangjunhd.blog.51cto.com/
Test.java
class MyObject {}
public class Test {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.clone(); // Compile error.
}
}
此时出现上文提到的错误:The method clone from the type Object is not visiuable.
我们已经清楚Object.clone()是protected方法。这说明,该方法不可以被不同包(java.lang)下和它(java.lang.Object)的子类访问。这里是MyObject类(默认继承java.lang.Object)。
同样Test也是java.lang.Object的子类。但是,不能在一个子类中访问另一个子类的protected方法,尽管这两个子类继承自同一个父类。
再看示例2:
Test2.java
class MyObject2 {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

public class Test2 {
public static void main(String[] args) throws CloneNotSupportedException {
MyObject2 obj = new MyObject2();
obj.clone(); // Compile OK.
}
}
这里,我们在MyObject2类中覆盖(override)父类的clone()方法,在另一个类Test2中调用clone()方法,编译通过。
编译通过的原因显而易见,当你在MyObject2类中覆盖clone()方法时,MyObject2类和Test2类在同一个包下,所以此protected方法对Test2类可见。
分析到这里,我们在回忆一下Java中的浅复制与深复制文中,章节2.2中的声明,②在派生类中覆盖基类的clone()方法,并声明为public现在明白这句话的原因了吧(为了让其它类能调用这个类的clone()方法,重载之后要把clone()方法的属性设置为public)。
下面再来看示例3:
Test3.java(重点)
package 1
class MyObject3 {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package 2
public class Test3 extends MyObject3 {
public static void main(String args[]) {
MyObject3 obj = new MyObject3();
obj.clone(); // Compile error.
Test3 tobj = new Test3();
tobj.clone();// Complie OK.
}
}
这里我用Test3类继承MyObject3,注意这两个类是不同包的,否则就是示例2的情形。在Test3类中调用Test3类的实例tobj的clone()方法,编译通过。而同样调用MyObject3类的实例obj的clone()方法,编译错误!
意想不到的结果,protected方法不是可以被继承类访问吗?
必须明确,类Test3确实是继承了类MyObject3(包括它的clone方法),所以在类Test3中可以调用自己的clone方法。但类MyObject3的protected方法对其不同包子类Test3来说,是不可见的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: