Hidden fields though inheritance

前端 未结 3 2017
别那么骄傲
别那么骄傲 2020-12-19 02:06

In the following code example:

class Parent { 
    int x =5;
    public Integer aMethod(){

        System.out.print(\"Parent.aMthod \");
        return x;
          


        
3条回答
  •  遥遥无期
    2020-12-19 02:47

    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).

提交回复
热议问题