【发布时间】:2015-05-23 05:52:30
【问题描述】:
我有一个子类对象。我可以在不使用 super 关键字的情况下访问超类的隐藏变量吗? ??实际上,我找到了一种技术..它的工作原理,但我不明白它背后的概念原因。
class A {
public int a = 5;
private int c = 6;
void superclass() {
System.out.println("Super class" + " " + "value of a is " + a);
System.out.println("Super class" + " " + "value of c is " + c);
}
}
class B extends A {
int b = 7;
int a = 8;
void subclass() {
System.out.println("Sub class" + " " + "value of b is " + b);
System.out.println("Sub class" + " " + "value of a is " + a);
}
}
class Demo {
public static void main(String args[]) {
A a1 = new A();
B b1 = new B();
b1.superclass();
}
}
在上面的代码中,如果b1是B类的一个对象,我调用了一个名为superclass()的超类方法;现在输出是a=5。但我的论点是为什么不能是 a=8 ? a=5 是隐藏的,要访问它,我们必须使用 super 关键字。但是在这里没有超级关键字我得到a=5。怎么可能?
【问题讨论】:
-
你的代码能编译吗?我投票结束这个问题作为题外话。
-
我不这么认为。我感觉他抄错了两行。我已经编辑了这个问题,一旦获得批准,它将更具可读性。 @ChetanKinger,旁注,我不觉得这是题外话。
-
@AnindyaDutta 代码无法编译。请阅读this
-
@ChetanKinger 现在可以了 :)
-
@AnindyaDutta 你只是鼓励更多的人变得懒惰并在这个美妙的网站上制造更多的混乱;)。
标签: java inheritance