【发布时间】:2013-06-20 11:50:45
【问题描述】:
这是同一个问题的稍微详细的版本。
我们无法访问子类中的(超类的)受保护变量,子类在不同的包中。我们只能访问超类的继承变量。但是,如果我们将修饰符更改为“受保护的静态”,那么我们也可以访问超类的变量。为什么会这样?
这是我试图解释的相同的代码 sn-p。
package firstOne;
public class First {
**protected** int a=7;
}
package secondOne;
import firstOne.*;
public class Second extends First {
protected int a=10; // Here i am overriding the protected instance variable
public static void main (String [] args){
Second SecondObj = new Second();
SecondObj.testit();
}
public void testit(){
System.out.println("value of A in Second class is " + a);
First b = new First();
System.out.println("value in the First class" + b.a ); // Here compiler throws an error.
}
}
上述行为是预期的。但我的问题是,如果我们将超类实例变量“a”的访问修饰符更改为“受保护的静态”,那么我们也可以访问该变量(超类的变量)......!我的意思是,
package firstOne;
public class First {
**protected static** int a=7;
}
package secondOne;
import firstOne.*;
public class Second extends First {
protected int a=10;
public static void main (String [] args){
System.out.println("value in the super class" + First.a ); //Here the protected variable of the super class can be accessed..! My question is how and why..?
Second secondObj = new Second();
secondObj.testit();
}
public void testit(){
System.out.println("value of a in Second class is " + a);
}
}
上面的代码显示了输出:
超类 7 中的值
test1 类中 x 的值为 10
这怎么可能……?
【问题讨论】:
-
我对为什么第一种情况不起作用感到更加困惑。根据the documentation on access control,我认为
a在这两种情况下都应该可见。 -
实例成员上的
protected不是只适用于this吗?即如果你想从子类访问它,你必须使用this;它不适用于任意实例。 -
@Thihara:我测试了他的代码(减去额外的
**s),我也得到了一个编译器错误:error: a has protected access in First。 -
@Prasad:呃,你没看懂我说的,我给你解释了!当您说
protected static时,这意味着this.a访问与b.a相同的变量,因此编译器允许第一个但阻止其他变量是没有意义的。当您只说protected时,this.a与b.a不同,因此编译器允许您访问this.a,但阻止您访问b.a。 -
@Prasad:呃,你的代码和我解释的不一样。你有一个额外的
protected int a=10;,它覆盖了First中的protected static a。那只会让你更加困惑。删除它,以便您了解为什么编译器会按照我告诉您的方式运行。然后在有意义后随意将其放回原处。
标签: java