Hidden fields though inheritance

[亡魂溺海] 提交于 2019-11-29 09:42:15
Arjan Tijms

There's no polymorphic resolution being done when you access class member fields (instance variables) like p.x. In other words, you'll get the results from the class that's known at compile time, not what is known at run time.

For method calls this is different. They are dispatched at run time to an object of the actual class the reference points to, even if the reference itself has a super type. (in the VM this happens via the invokevirtual opcode, see e.g. http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#invokevirtual).

kosa

Operations are always on Objects. In both cases, p.aMethod() and c.aMethod(), object is child that is why it printed 6 in both cases. When you directly access variable directly it reads variable associated with left side.

Because declaring a variable doesn't inherit. You have two copies of x in the class, one in parent namespace, one in child namespace.

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