Polymorphism: A variable of the same type, when the same method is called, presents many different behavioral characteristics, which is polymorphic.
1. A reference variable can only invoke the method that its compile-time type has when it is compiled, but the runtime executes the method it has with the run-time type , so when writing Java code. A reference variable can only invoke methods contained in the class used to declare the variable, for example, by defining a variable P with the object p = new person () code, this p can only call methods of the object class, not the method defined in the person class.
2. Unlike methods, instance variables of an object are not polymorphic.
3. Forced conversions between reference variables
- Conversions between base class types can only be performed between numeric types.
- conversions between reference types can only be done between two types that have an inheritance relationship. Before forcing a type conversion, the instanceof operator is used to determine whether a successful conversion can be performed, thereby avoiding the classcastexcepetion exception. For example:
if instanceof String) { = (String) objpri;}
instanceof operator Note: The compile-time type of the operand preceding the instanceof operator is either the same as the following class, or it has a parent-child inheritance relationship with the following class, or it causes a compilation error.
Java Polymorphism (caveats)