|
Intera A;
A= new B ();
A.fun ();
A = new C ();
A.fun ();
}
} |
The output results are:
This is B
This is C
In the example above, Class B and Class C are two classes that implement Interface Intera. Implementing the Interface Method Fun (), by assigning the instance of Class B and Class C to interface reference A, we implement the dynamic binding of the method at runtime, and make full use of "one interface, multiple methods" to show the dynamic polymorphism of Java.
One thing to note is that when Java uses an interface variable to invoke its method of implementing the object of the class, the method must already be declared in the interface, and the type and parameters of the implementation method in the implementation class of the interface must match exactly as defined in the interface.
Conclusion: The above is the Java Run-time polymorphism of the implementation method, everyone in the programming process can be flexible to use, but in the performance requirements of the code does not advocate the use of run-time polymorphism, after all, Java Run-time dynamic method calls compared to the ordinary method calls the system overhead is relatively large.