|
Intera; A = new B (); A. Fun (); A = new C (); A. Fun (); } } |
Output result:
This is B
This is C
In the preceding example, class B and class C are two classes that implement interface intera, respectively implementing the interface method fun (), by assigning instances of class B and class C to interface reference A, the dynamic binding of methods during runtime is realized, making full use of "one interface, multiple methods "demonstrate the dynamic polymorphism of Java.
Note that when Java uses interface variables to call its method for implementing class objects, this method must have been declared in the interface, in addition, in the interface implementation class, the types and parameters of the implementation method must be exactly matched with the defined in the interface.
Conclusion: The above is the implementation method of Java Runtime polymorphism. You can use it flexibly in the programming process, but it has high performance requirements.CodeWe do not advocate the use of Runtime polymorphism. After all, the system overhead of dynamic method calling in Java Runtime is relatively large than that in common method calling.