A polymorphism is the ability of the same behavior to have multiple different manifestations or forms. Polymorphism is the same interface, which uses different instances to perform different operations.
Polymorphism is the embodiment of multiple expressions of objects, such as:
In reality, we press the F1 key:
If the AS 3 help document is currently popping up under the Flash interface, if the Word is currently popping up under the Word is currently popping up under the Windows Help and Support
Three necessary conditions for polymorphism
Inheritance override parent class reference pointing to child class object
Parent p = new Child();
When calling a method using polymorphic method, first check whether the method is in the parent class. If not, there will be a compilation error; if so, then call the method of the subclass with the same name.
example
package Wangyi;class Base{public void method() {System.out.println("Base");}}class Son extends Base{public void method() {System.out.println("Son");}}public void methodB() {System.out.println("SonB");}}public class Test01{public static void main(String[] args) {Base base = new Son();base.method();base.methodB();}}Ask about the output results of this program. (D)
A. Base SonBB. Son SonBC. Base Son SonBD. Compilation does not pass explanation: Base base=new Son(); is a polymorphic representation. The parent class object calls the subclass and creates the Son object. The method() method called by base is called the method() method overridden by the subclass. At this time, base still belongs to the Base object. When base calls methodB(), this method does not exist in the Base object, so the compilation cannot be passed. To call, you need to cast SON son=(SON)base; first, and then call with son.methodB().
Summarize
The above is all about the Java polymorphic instance code in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!