The Java polymorphism has always been a difficult point for us to understand. After reading "In-depth understanding of Java Virtual machines" and "Java Programming ideas", I feel more deeply understanding.
We know that when a parent class reference is directed to a subclass object, and the child class overrides an interface in the parent class, when this interface is called with a parent class reference, the interface in the subclass object is actually called.
In fact, it is not difficult to understand this point, first of all to clarify the following two points:
1. Why can a parent reference point to a subclass object?
Subclasses are inherited by the parent class, so the subclass contains all the interfaces in the parent class. Their relationship is a is-a relationship, which can be replaced by a subclass in any place where the parent class is used, which is the principle of the Richter substitution.
The Richter substitution principle (Liskov Substitution Principle, LSP): All references to the base class (parent class) must be able to transparently use objects of its subclasses.
2. How is the method of the object called?
Associating a method call with a method body in Java is called binding. If you can bind before the program executes, it is called early binding . Binding at run time based on the object's specific type is late binding , also known as dynamic binding or run-time binding.
Myth: A method call that does not satisfy a polymorphic condition is a pre-binding, assuming that only the implementation of polymorphism is late binding. (That's what I understood before)
The only static and final decorated methods in Java are early binding, and all other methods are late-bound! That is, late binding occurs spontaneously, and the message sent to an object must be based on the actual type of the object to find the method defined in the class. How is this implemented? My simple comprehension is as follows: In the JVM, we locate an object by a reference, and the object also stores the type information of the object itself (pointing to the class object in the method area), which is why we can use the GetClass () method to get the class of the object. When sending a message to an object, we must also find the object's type information, and then find the appropriate method in that class.
Understanding of Java Multiple Units 2