Please go to DobbyKim’s Question of the Day for more questions

A program:

public class Polymorphic {
    public static void main(String[] args) {
        Animal cat = newCat(); System.out.println(cat.name); }}class Animal {
    String name = "animal";
}
class Cat extends Animal{
    String name = "cat";
}
Copy the code

Program 2:

public class Polymorphic {
    public static void main(String[] args) {
        Animal cat = newCat(); cat.speak(); }}class Animal {
    public void speak(a){
        System.out.println("I am an animal"); }}class Cat extends Animal{
    @Override
    public void speak(a) {
        System.out.println("I am a cat"); }}Copy the code

A:

The output of program 1 is:

animal
Copy the code

The output of program 2 is:

I'm a catCopy the code

Is polymorphic. It is important to note that polymorphism is divided into compile-time polymorphism and run-time polymorphism.

  • In polymorphic applications, member variable access features: compile to the left, run to the left
  • In polymorphic applications, member method calls are characterized by compiling to the left and running to the right

For program 1, at compile time, the JVM looks at Animal cat = new cat (); If (name = Animal) {if (name = Animal) { At runtime, for member variables, the JVM still looks to the left to retrieve the parent class’s member variables.

For program 2, the JVM looks at Animal cat = new cat () at compile time; Does the class to the left of the equals sign have this method? If so, the compilation succeeds; if not, the compilation fails. When the program runs, it depends on how the object to the right of the equal sign implements the method, so the final result is the result of the object to the right overwriting the method.