Why aren't Java fields polymorphic?

社会主义新天地 提交于 2019-12-31 01:53:50

问题


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

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.

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

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?

Edit: 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.


回答1:


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

  • invokedynamic
  • invokeinterface
  • invokespecial
  • invokestatic
  • 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



来源:https://stackoverflow.com/questions/43407138/why-arent-java-fields-polymorphic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!