java 协变返回类型
为什么下面的代码打印“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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为你指的是字段,它不受多态性的影响。如果您改为使用
getX()
,它将返回2
。您要问的是,类
A
中定义的字段x
的值(因为Base.getObject()
返回A)。即使
CovariantReturn
重写返回B
的方法,您也不会将您的对象引用为CovariantReturn
。稍微扩展一下字段如何不受多态性的影响 - 字段访问是在编译时实现的,因此无论编译器看到什么,这就是访问的内容。在您的情况下,该方法定义返回
A
,因此可以访问Ax
。另一方面,方法是根据运行时类型调用的。因此,即使您定义返回A
但返回B
的实例,您调用的方法也会在B
上调用。Because you are referring to fields, which are not affected by polymorphism. If you instead used
getX()
, it would've returned2
.What you are asking is, the value of field
x
defined in classA
(becauseBase.getObject()
returnsA
). Even thoughCovariantReturn
overrides the method to returnB
, you are not referring to your object asCovariantReturn
.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 soA.x
is accessed. On the other hands methods are invoked based on the runtime type. So even if you define to returnA
but return an instance ofB
, the method you invoke will be invoked onB
.@kris979虽然你返回B,但我认为区别在于返回类型是A。因此打印A中x的值,即1。
@kris979 Though you are returning B, i think what makes the difference is that the return type is of A. Hence value of x in A i.e. 1 is printed.
正如 Bozho 指出的那样 - 实例变量永远不会受到多态性的影响。让我给你一个简单的小例子。
此代码将打印 - in sub and 1
As Bozho pointed out - instance variable are never affected by polymorphism. Let me give you a quick small example.
This code will print - in sub and 1