Java – polymorphism of member variables I know it’s impossible. I don’t understand the specific situation

I know this behavior, but I'm not 100% sure why it happened

class Animal{  
   String name = "Animal";  
   public void display(){  
    System.out.println("My name is "+ name);  
   }  
}  

public class Dog extends Animal {   
   String name = "Dog";   

   public static void main(String[] args) {  
        Animal a = new Dog();  
        Dog d = new Dog();  
        System.out.println(a.name);//Line 1  
        a.display();//Line 2   
        d.display();//Line 3  
   }  
}

I promise on line 1 that it will show the animal because it is statically typed (solved by the compiler) What puzzles me is why line 3 also shows that my name is an animal? This method will try to call on the dog, because this is the actual object at runtime, and since it is not overwritten, this method will be found in the parent class animal What I don't get is why the name of the parent class is used in the method display if the actual object of the operation is dog Won't it hide the parent name variable? It doesn't seem like my static solution because the type is dog Isn't this part of the memory layout of oject? This is like an internal display where only the parent variable is visible Why?

to update:

@Razvan and @ Louis Wasserman's answers have always been helpful Here is my last question: the views of both seem to be as follows: from @ razyan system out. println(“My name is”this.name); //< - Note that this comes from @ Louis, which means animals, and () is implemented in the animal class

So far so good, but how are these points the same as modifying display () as follows?

class Animal{  
   String name = "Animal";  
   public void display(){  
    System.out.println("Current class is "+ this.getClass().getName());  
    System.out.println("My name is "+ name);  
   }  
}

Then the results are as follows:

Dog d = new Dog();  
 d.display();

I expect this exhibition will be about animals, because I understand the answer here But not Why?

Solution

When you call D. display (), animal. Is called Display (), because you don't want to override it in the dog class

So dog The imaginary implementation of display () will be as follows:

public void display(){  
    super.display();
 }

And animal The implementation of display() is:

public void display(){  
    System.out.println("My name is "+ this.name); //<-- note the this
 }

Animal. The display () method doesn't even know that an object dog exists, so its name is a variable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>