在不同的包里, 但属于继承关系的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);
}
}为什么会出错? 请高手帮忙谢谢!
举个例子:在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);
}
}为什么会出错? 请高手帮忙谢谢!
你的意思是AA继承Person吧。是可以访问父类的protected的变量的。但你写的有问题。main 方法是static的,所以在类AA没有被实例化就可以调用,但变量p是非static的,所以要先实例化类之后,才可以访问p。
举个例子:在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修饰的变量的例子, 谢谢!
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
你把Person这个类写出来,后面不用的吗?