在不同的包里, 但属于继承关系的2个类能访问protected修饰的变量吗?
举个例子:在com文件夹里:
public class Person {
    protected int p = 9;
}
在com\test文件夹里:
public class AA extends A {
    public static void main(String[] args) {
        System.out.println(p);
    }
}为什么会出错? 请高手帮忙谢谢!

解决方案 »

  1.   


    你的意思是AA继承Person吧。是可以访问父类的protected的变量的。但你写的有问题。main 方法是static的,所以在类AA没有被实例化就可以调用,但变量p是非static的,所以要先实例化类之后,才可以访问p。
      

  2.   

    可以,main是静态方法,不能直接访问非静态的p
      

  3.   

    main 里,必须先生成一个对象,才能调用非静态的方法,基础很重要。
      

  4.   

    不好意思~ 我写错了, 请看以下我重新写的程序:在不同的包里, 但属于继承关系的2个类能访问protected修饰的变量吗? 
    举个例子:在com文件夹里: 
    public class Person { 
        protected int p = 9; 
    }
    在com\test文件夹里: 
    public class AA extends A { 
    }
    出现了以下错误信息:
    AA.java:1: 找不到符号
    符号: 类 A
    public class AA extends A {
                            ^
    1 错误
    为什么连继承都会出错? 请高手帮忙谢谢!还有一个问题, 请高手帮忙写一个例子, 一个关于在不同的包里, 但属于继承关系的2个类能访问protected修饰的变量的例子, 谢谢!
      

  5.   

     父类
    package beans;
    public class Father {
    protected String f = "father";
    }
    子类
    package lottery;
    import beans.Father;
    public class Son extends Father {
    public static void main(String[] args) {
            Son s = new Son();
           System.out.println(s.f);
    }
    }
    输出结果:father
      

  6.   

    A是哪个类?
    你把Person这个类写出来,后面不用的吗?