search

Home  >  Q&A  >  body text

java - When a member variable with the same name is called polymorphically, why is the member variable of the parent class accessed?

I just guessed that since the member variables of the parent class and the subclass are each stored in the heap, it may be because of the existence of the parent class, so the member variables of the parent class are found first. Then I tested it, the code is as follows:

package test;

public class Polymorphism {
    public static void main(String[] args) {
        F f = new Z();
        f.show();
        System.out.println("f:"+f);
        System.out.println("f:"+f.a);
    }
}

abstract class F{
    int a = 10;
    public abstract void show();
}
class Z extends F{
    int a = 5;
    public void show(){
        System.out.println("Z:"+this);
        System.out.println("Z:"+this.a);
    }
}

The output is:
Z:test.Z@15db9742
Z:5
f:test.Z@15db9742
f:10

f and this point to the same object and access the same variable but have different results, so my guess above should be wrong. So what exactly causes polymorphic calls to member variables with the same name to access member variables of the parent class?

女神的闺蜜爱上我女神的闺蜜爱上我2727 days ago938

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-06-12 09:29:03

    f refers to subclass objects. I have only heard of rewriting and overloading of methods, but not of class variables. The program I ran depends on the situation. If a method is called, it is the actual object pointed to (the actual object here is a subclass The method of object Z), if the class variable has the same name, is the class variable value of the living object.

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-12 09:29:03

    Rewriting, overloading and dynamic linking of methods in Java constitute polymorphism. Polymorphism is different expressions of the same thing.

    Your example is polymorphism demonstrated by method rewriting.

    What is declared is the parent class F, which actually points to its subclass Z. This is equivalent to an upward type conversion, because Z is also inherited from F, so it can be upwardly converted. Now Z is of type F.

    So here the f variable is instantiated by Z, but it is of type F and shows the characteristics of F.

    reply
    0
  • Cancelreply