This article describes the dynamic method scheduling of Java. Share it for your reference, as follows:
Dynamic method scheduling:
1. Access a non-static method of a referenced variable, and binds the method of the actual referenced object at runtime.
2. Access a static method of a referenced variable, which is bound to the declared class method at runtime.
3. Access the member variables of a referenced variable (including static variables and instance variables), and bind the member variables of the declared class at runtime.
Point 3: Pay special attention, I have never noticed it before
1. Non-static methods:
public class Person {public String name; public void getInfo() { System.out.println("parent class"); }}public class Student extends Person { public void getInfo() { // Method override super.getInfo(); // Call the parent class method System.out.println("subclass");}public static void main(String[] args) { Person s = new Student(); Person t = new Person(); s = t; // The object type of S is the parent class, that is, Person class s.getInfo();}}The result of the run is: parent class
2. Static method:
public class Person {public String name; public static void getInfo() { System.out.println("parent class"); }}public class Student extends Person {Publics static void getInfo() { // Method override System.out.println("subclass");}public static void main(String[] args) {Person s = new Student();s.getInfo(); //Equivalent to Person.getInfo();}}The result of the run is: parent class
3. Member variables
public class erson {public String name = "father"; public void getInfo() { System.out.println("parent class"); }}public class Student extends Person {public String name = "son";public void getInfo() { // Method override super.getInfo(); // Call the parent class method System.out.println("subclass");}public static void main(String[] args) {Person s = new Student();Person t = new Person();s = t;System.out.println(s.name);}}Running result: fanther
The same is true for changing member variables to static types
In addition, for the following two variables
Students = new Student();Person t = new Student();
However, there is actually a difference between the two. When the subclass Student has its own personalized method (not in the parent class), for example, there is a method
public goSchool(){}Then only s can call this goSchool method
t cannot be called
I hope this article will be helpful to everyone's Java programming.