Polymorphism is one of the "three major characteristics" of object-oriented thinking, the remaining two are encapsulation and inheritance respectively.
Through inheritance, a class can be used as more than one data type, he can be made to represent the data type (which is most commonly used), but also as his arbitrary base class represented by the data type or any interface type---the previous question is this class implementation of this interface.
For polymorphism, it can be summed up as:
One, a reference to the child class using the parent class type;
Second, the reference can only invoke methods and variables defined in the parent class;
Thirdly, if a method in the parent class is overridden in a subclass, the method in the subclass is called when the method is called; (dynamic connection, dynamic invocation)
Variables cannot be overridden (overwritten), the concept of "overriding" is only for methods, and if a variable in the parent class is "overridden" in a subclass, an error is made at compile time.
Polymorphism: Sends a message to an object, allowing the object to decide for itself what behavior to respond to.
Implementing a dynamic method call by assigning a subclass object reference to a superclass object reference variable
For a specific example, see the following code:
Class father{
public void Func1 () {
Func2 ();
}
This is the Func2 () method in the parent class, because the method is overridden in the following subclass
So when called in a reference to a parent class type, this method is no longer valid
Instead, the Func2 () method that will be overridden in the calling subclass
public void Func2 () {
System.out.println ("AAA");
}
}
Class Child extends father{
func1 (int i) is an overload of the Func1 () method
Because this method is not defined in the parent class, it cannot be called by a reference of the parent class type
So in the following Main method, CHILD.FUNC1 (68) is wrong.
public void func1 (int i) {
System.out.println ("BBB");
}
Func2 () overrides the Func2 () method in the parent class father
If the Func2 () method is called in a reference to the parent class type, then this method must be overridden in the subclass
public void Func2 () {
System.out.println ("CCC");
}
}
public class Polymorphismtest {
public static void Main (string[] args) {
Father child = new Child ();
CHILD.FUNC1 ();//What will the print result be?
}
}
What is polymorphic