JAVA polymorphism and java Polymorphism
Polymorphism separates interfaces and implementations from each other by separating what to do and how to do them.
Inheritance allows an object to be treated as its own type dynamic type.
Method call binding
Binding: associate a method call with a method subject.
Pre-binding: bind the program before it is executed (if any, implemented by the compiler and the Connection Program ).
Post-binding (also calledDynamic bindingOr bind at runtime): bind an object based on its type during runtime (determine the actual type of the referenced object during execution and call its corresponding method based on its actual type)
In Java, the pre-binding methods are as follows:
Static Method (the constructor belongs to the static method, but the static declaration is a hermit ),
Final method (private method belongs to final method)
- The final method prevents others from overwriting the method. The final method can effectively "close" dynamic binding.
(All domain access operations are parsed by the compiler., So it is not a polymorphism)
Method Call Sequence
Attributes, methods, constructor methods, and free blocks are all members of the class. When creating class objects, the execution sequence of the members of the class is as follows:
1. The static members and static initialization of the parent class are fast and executed in sequence when the code appears.
2. Subclass static members and static initialization blocks are executed in order of code appearance.
3. The instance members and instance initialization blocks of the parent class are executed in order of code appearance.
4. constructor of the parent class (if it is not explicitly specified to call the constructor of a parent class, the default constructor of the parent class will be called by default. If there is no default constructor, the compiler will
Error)
5. Subclass instance members and instance initialization blocks are executed in order of code appearance.
6. constructor of subclass.
(Source: lgfeng218)
An effective criterion for writing constructor: (Java programming ideology Fourth Edition Chinese P163)
"Use the simplest possible method to make the object normal. If possible, avoid calling other methods." The only method in the constructor that can be safely called is the final method in the base class.
Polymorphism Conditions
1. Inheritance required
2. Rewrite
3. parent class references to subclass objects
The role of polymorphism: Eliminate the coupling relationship between classes.