Dynamic binding in polymorphism

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right


1. What is dynamic binding

In Java, when a method of a certain class is called, which piece of code is executed (the code of the parent method or the code of the subclass method) depends on whether the reference refers to the parent class object or the subclass object. This process It is determined when the program is running (not during compilation), so it is called dynamic binding.

2. Simple example

people class

class people {
    
    
    public int age=100;
    public String name;
    public void look(){
    
    
        System.out.println("人在看手机");
    }
}

student class

public class student extends people{
    
    
    public String school;
    public int age=10;
    public void look(){
    
    
        System.out.println("学生在看书");
    }
}

Main function

public class Main {
    
    
    public static void main(String[] args) {
    
    
        people p1=new people();
        p1.look();
        people p2=new student();
        p2.look();
    }
}

operation result
Insert picture description here

3. Matters needing attention

Both p1 and p2 are references of the people type, but the former points to an instance of the people type, and the latter points to an instance of the student type.
It can be concluded from the running results that the instance that points to the parent class calls the look method of the parent class version, and the instance that points to the child class calls the look method of the subclass version.
If the look method exists in both the parent class and the child class, and the parameters are different, then calling look will not involve dynamic binding. It will judge whether there is a matching method in the parent class according to the type and number of the incoming parameters. If not, it will compile and report an error.

Guess you like

Origin blog.csdn.net/weixin_45070922/article/details/112971414