日期:2014-05-20  浏览次数:20695 次

关于java访问控制符的问题.
package   father;

public   class   Father   {
public   String   publicFatherString= "Father类的public成员变量 ";
protected   String   protectedFatherString= "Father类的protected成员变量 ";

public   void   publicFatherClassMethod()   {
System.out.println( "Father类的public方法 ");
}

protected   void   protectedFatherClassMethod()   {
System.out.println( "Father类的protected方法 ");
}
}
--------------------------------------
package   children;
import   father.Father;

public   class   Children   extends   Father{
public   String   publidChildString= "子类public成员变量 ";
protected   String   protectedChildString= "子类的protected成员变量 ";

public   void   publicChildClassMethod()   {
System.out.println( "child类的public方法 ");
}

protected   void   protectedChildClassMethod()   {
System.out.println( "child类的protected方法 ");
}
}

--------------------------------------
package   children;
import     father.Father;

public   class   Hello   {
public   void   nihao()   {
Children   child   =   new   Children();

//child.protectedFatherClassMethod();
                                    上面被注释的方法无法在Hello类中看到.
        Children类继承了Father类,当然也继承了Father类的
        被保护的方法-protected   void   protectedFatherClassMethod()
        换句话说Children类拥有Father类的
        protected   void   protectedFatherClassMethod()方法,
        Hello类与Children类在相同的包内(children),按照protected
        的访问级别在Hello类中应该可以通过Clildren实例的引用执行
        Father类的protected   void   protectedFatherClassMethod()方法.
        实际的情况是不可以访问的.
           

        小生谢谢,各位大侠了.


}
}


------解决方案--------------------
public 成员变量和方法可以被它的直接子类和间接子类继承,可以跨包访问,

protected 成员变量和方法可以被它的直接子类和间接子类继承,但条件为同一包内。

------解决方案--------------------
赞!
------解决方案--------------------
private 只能在同一方法,或同一类中使用

------解决方案--------------------
不在一个包中
------解决方案--------------------
同一个类 子类 同一个包 所有类
public √ √ √ √
default √ √ √
protected √ √
private √