为什么两种情况下的输出不同? [英] Why is the output different in the two cases?
本文介绍了为什么两种情况下的输出不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么输出在以下情况下有所不同,即使该变量已被覆盖?
Why is the output different in the below case even when, the variable has been overridden?
public class A {
int a = 500;
void get() {
System.out.println("a is " + this.a);
}
}
public class B extends A {
int a = 144;
}
public class mainmethod {
public static void main(String args[]) {
B ob = new B();
System.out.println("a is " + ob.a);
ob.get();
}
}
推荐答案
那里不是被重写的变量。 B
实际上有两个实例变量,名为 a
:一个声明,另一个继承。见:
There is no such thing as overridden variables. B
actually has two instance variables named a
: one it declares and another it inherits. See this:
B ob = new B();
System.out.println("B.a is " + ob.a);
System.out.println("A.a is " + ((A)ob).a);
在 B
的实例方法中你可以写 super.a
或((A)this).a
来访问父变量。
Inside a B
's instance method you can write super.a
or ((A)this).a
to access the parent's variable.
这篇关于为什么两种情况下的输出不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文