2013-05-26 63 views
1

我有这些类:爪哇 - 保护的访问修饰符

package abc; 

public class A { 

    public int publicInt; 
    private int privateInt; 
    protected int protectedInt; 
    int defaultInt; 

    public void test() { 
     publicInt = 0; 
     privateInt = 0; 
     protectedInt = 0; 
     defaultInt = 0; 
    } 

} 

“A”包含了所有四个访问修饰符的属性。这些其他类扩展“A”或创建实例并尝试访问属性。

package de; 

public class D { 

    public void test() { 
     E e = new E(); 
     e.publicInt = 0; 
     e.privateInt = 0; // error, cannot access 
     e.protectedInt = 0; // error, cannot access 
     e.defaultInt = 0; // error, cannot access 
    } 

} 

package de; 

import abc.A; 

public class E extends A { 

    public void test() { 
     publicInt = 0; 
     privateInt = 0; // error, cannot access 
     protectedInt = 0; // ok 
     defaultInt = 0; // error, cannot access 
    } 

} 

package abc; 

import de.E; 

public class C { 

    public void test() { 
     E e = new E(); 
     e.publicInt = 0; 
     e.privateInt = 0; // error, cannot access 
     e.protectedInt = 0; // ok, but why? 
     e.defaultInt = 0; // error, cannot access 
    } 

} 

一切都好,除了我不明白,为什么在C类,我可以访问e.protectedInt。

回答

1

我认为一个代码插图可以帮助我们更好地理解。

,E类添加一个受保护的成员现在

public class E extends A { 
    protected int protectedIntE; 
    ... 

,尝试在类访问它ç

e.protectedInt = 0; // ok, but why? 
e.protectedIntE = 0; // error, exactly as you expected 

所以,这里要注意的一点是,尽管你通过一个实例访问protectedIntE它实际上属于A类,并且通过继承被E类继承。类E的实际(非继承)保护成员仍然无法像您期望的那样访问。

现在,由于A类和C类在同一个包中,受保护的访问基本上作为包的超集(也包括子类访问),所以编译器在这里没有什么可抱怨的。

1

因为CA(包abc)位于同一包中,并且在Java中的protected修饰符包括在同一包中的访问。

0

Acces Control

按照链接,你到了Java文档,explanes修饰符accessibalities。

protected对于您当前的类,包和子包,类,函数等是可见的。也可以在你班的子类中看到。