java协变量返回类型 [英] java covariant return type
问题描述
为什么下面的代码显示"1"?
Why does below code prints "1" ?
class A {
int x = 1;
}
class B extends A {
int x = 2;
}
class Base {
A getObject() {
System.out.println("Base");
return new B();
}
}
public class CovariantReturn extends Base {
B getObject() {
System.out.println("CovariantReturn");
return new B();
}
/**
* @param args
*/
public static void main(String[] args) {
Base test = new CovariantReturn();
System.out.println(test.getObject() instanceof B);
System.out.println(test.getObject().x);
}
}
推荐答案
因为您是指不受多态性影响的字段.如果您改用getX()
,它将返回2
.
Because you are referring to fields, which are not affected by polymorphism. If you instead used getX()
, it would've returned 2
.
您要问的是,类A
中定义的字段x
的值(因为Base.getObject()
返回A
).即使CovariantReturn
覆盖了返回B
的方法,您也没有将对象称为CovariantReturn
.
What you are asking is, the value of field x
defined in class A
(because Base.getObject()
returns A
). Even though CovariantReturn
overrides the method to return B
, you are not referring to your object as CovariantReturn
.
为了进一步说明字段如何不受多态性影响-字段访问是在编译时实现的,因此无论编译器看到什么,这就是访问的内容.在您的情况下,该方法定义为返回A
,因此可以访问A.x
.另一方面,基于运行时类型调用方法.因此,即使您定义返回A
但返回B
的实例,您调用的方法也会在B
上调用.
To expand a bit on how fields are not affected by polymorphism - field access is realized at compile time, so whatever the compiler sees, that's what's accessed. In your case the method defines to return A
and so A.x
is accessed. On the other hands methods are invoked based on the runtime type. So even if you define to return A
but return an instance of B
, the method you invoke will be invoked on B
.
这篇关于java协变量返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!