[英]Why does the object refers to the value of the parent class instead of the class it is assigned to?
Can someone explain why the output is 10 and not 20?有人可以解释为什么输出是 10 而不是 20? Why does the object refers to the value of the parent class instead of the class it is assigned to?
为什么对象引用的是父类的值而不是指派给它的类?
class A {
int i = 10;
}
class B extends A {
int i = 20;
}
public class MainClass {
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
}
}
The instance you're creating is of type A
, so since both variables have the same name, you'll get the superclass' one, if you want B
's you should do您正在创建的实例的类型为
A
,因此由于两个变量具有相同的名称,您将获得超类之一,如果您想要B
,则应该这样做
B b = new B()
System.out.println(b.i)
You shouldn't use variables of the same name like that in between superclasses and subclasses, gets very confusing and kinda defeats the purpose of inheriting.你不应该在超类和子类之间使用同名的变量,这会变得非常混乱并且有点违背继承的目的。
Can someone explain why the output is 10 and not 20?
有人可以解释为什么输出是 10 而不是 20?
Since the value of i
is defined in the class A
and is NOT overridden/re-assigned by the definition of class B
as you might just be assuming.由于
i
的值是在class A
定义的,并且不会像您假设的那样被class B
的定义覆盖/重新分配。 Adding a custom constructor could clarify your doubts further of what you might be intending to do:添加自定义构造函数可以进一步澄清您对可能打算做什么的疑虑:
class A {
int i = 10;
}
class B extends A {
public B() {
this.i = 20;
}
}
A a = new B();
System.out.println(a.i); // would now print 20
Declaring the same variable i
in class B
would have its own scope and does not inherit from the class A
.在类
B
声明相同的变量i
将有自己的作用域,而不是从类A
继承。
Variables can not be overridden in Java as they are resolved at compile-time;变量不能在 Java 中被覆盖,因为它们是在编译时解析的; You can use
super
to set its values,您可以使用
super
设置其值,
class A {
int i = 10;
}
class B extends A {
int i = 20;
public B() {
super();
super.i = i;
}
}
A a = new B();
System.out.println(a.i); //20
In Java, methods are overridden not variables.在 Java 中,方法被覆盖而不是变量。 So variables belong to their owner classes.
所以变量属于它们的所有者类。
a
is a reference of type A
that point to an object of type B
but remains of type A
. a
是类型A
的引用,它指向类型B
的对象,但仍为类型A
。 To call the i
of B
, you have to cast a
to B
.要调用
B
的i
,您必须将a
为B
。
A a = new B();
System.out.println(((B)a).i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.