为什么Java字段不是多态的? [英] Why aren't Java fields polymorphic?

查看:126
本文介绍了为什么Java字段不是多态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看答案,但我不理解为什么方法将是多态的而不是逻辑的背后的逻辑领域.

I was looking at this answer, and I don't understand the logic behind why methods would be polymorphic but not fields.

默认情况下,所有成员函数在Java中都是多态的.那意味着 当您调用this.toString()时,Java使用动态绑定来解析 调用,调用子版本.当您访问成员x时,您 访问您当前范围的成员(父亲),因为成员 不是多态的.

All member functions are polymorphic in Java by default. That means when you call this.toString() Java uses dynamic binding to resolve the call, calling the child version. When you access the member x, you access the member of your current scope (the father) because members are not polymorphic.

当您在基类中调用以下内容时,在父类和子类中都具有某些字段x,并且在子类中覆盖toString时:

When you have some field x in both the super and subclass, and override toString in your subclass, when you call the following in the base class:

System.out.println(this); //calls the subclass's toString implementation
System.out.println(this.x) //prints the base class's x field

在开头链接的问题中列出的答案中,这样做的理由是,基类在自己的范围内时不会知道"子类,但是对于多态而言,这是同一回事:超类不知道子类存在,但仍然调用子类方法.那么Java到底在做什么,使这两种行为有所不同-一种在子类中使用动态绑定,另一种则保持超类的作用域?

The justification for this in the answers listed in the question linked at the beginning is that the base class doesn't "know" about the subclass when it is in its own scope, but with polymorphism, it's the same thing: the superclass doesn't know the subclass exists, yet the subclass method is still called. So what exactly is Java doing that makes the two act differently - one using dynamic binding in the subclass and one keeping the scope of the superclass?

为澄清起见,我一直坚持为什么this.x将执行与多态相同的操作,查看对象的实际类型,而不仅仅是引用类型,并从子类中打印x字段

to clarify, I'm stuck on why this.x will do the same thing as polymorphism, look at the actual type of the object, not just the reference type, and print the x field from the subclass.

推荐答案

要实现子类型多态性,Java需要跟踪要调用的方法,这需要额外的开销.您可以通过将字段保持私有并使用getter来实现某种多态字段"(前者不是必需的,但很明智).您可能会对结帐感兴趣

To achieve subtype polymorphism Java needs to keep track of which method to call, it requires additional overhead. You could achieve kind of "polymorphic fields" by keeping fields private and using getters (the former is not required, but sensible to do). You may be interested in checking out

  • 动态调用
  • 调用界面
  • 调用特殊
  • 调用静态
  • 调用虚拟

通话.您可以在这里阅读更多有关它的信息: https://docs. oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokevirtual

calls. You may read more about it here: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokevirtual

这篇关于为什么Java字段不是多态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆