张洪伟ID:Jackiezhw
11613次访问,排名9532(-1)好友0人,关注者0
Jackiezhw的文章
原创 28 篇
翻译 0 篇
转载 8 篇
评论 0 篇
最近评论
文章分类
收藏
    相册
    Java Techonology
    BlogJava上圆月弯刀的Blog
    Java 调试平台
    自我成长
    存档
    软件项目交易
    订阅我的博客
    XML聚合  FeedSky
    订阅到鲜果
    订阅到Google
    订阅到抓虾
    订阅到BlogLines
    订阅到Yahoo
    订阅到GouGou
    订阅到飞鸽
    订阅到Rojo
    订阅到newsgator
    订阅到netvibes

    转载 Java的访问控制收藏

    新一篇: 我要学习的技术 | 旧一篇: 一个笔试题的分析

    默认的时候可以被同一类和它的子类访问,同一包和其他包中的类不可以访问;

    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.


    protected 访问需要格外小心。假定一个类A声明了一个protected 的域x,A被B继承,B被定义在一个不同的包中。 类B继承了这个保护域x,在B的当前实例中或者在B的任何实例中,它的代码是可以访问x的。但这并不表明B可以访问任何A的实例的protected域,如果一个对象是A的实例,但不是B的实例,那么它的域就没有被B继承,类B的代码也就不能访问它。

     

    package mypack1;
    public class ClassA {
    public int var1;
    protected int var2;
    int var3;
    private int var4;

    public void method(){
    var1
    =1;
    var2
    =1;
    var3
    =1;
    var4
    =1;

    ClassA a 
    = new ClassA();
    a.var1
    =1;
    a.var2
    =1;
    a.var3
    =1;
    a.var4
    =1;
    }

    }

    在另外一个包 mypackage2中 存在ClassA的一个子类 ClassC

    package mypack2;
    import mypack1.ClassA;
    class ClassC extends mypack1.ClassA{
    public void method(){
    ClassA a 
    = new ClassA();
    a.var1
    =1;
    a.var2
    =1//此行出错
    }
     
    }

    在出错那一行,变量var2是具有protected的,ClassC 可以访问从父类继承的ClassA的protected域,但是不能用ClassA的实例访问它。下面的代码演示了如何使用var2:

    package mypack2;
    import mypack1.ClassA;
    class ClassC extends mypack1.ClassA{

    public void method(){
    ClassA a 
    = new ClassA();
    a.var1
    =1;
    super.var2=1;
    ClassC c 
    = new ClassC();
    c.var1
    =1;
    c.var2
    =1;
    }

    }

    super.var2访问就是从父类继承来的protected变量,而因为c是ClassC的实例,并且在ClassC的代码中调用,是可以的,c这个对象如果放在其他的类中,它依然不能访问var2。


     

    发表于 @ 2007年10月11日 20:40:00|评论(loading...)|编辑

    新一篇: 我要学习的技术 | 旧一篇: 一个笔试题的分析

    评论:没有评论。

    发表评论  


    当前用户设置只有注册用户才能发表评论。如果你没有登录,请点击登录
    Csdn Blog version 3.1a
    Copyright © Jackiezhw