Method Overlay:
It's not just a matter of naming, but a fundamental feature in Java.
It is based on the concept of dynamic method dispatch.
Dynamic Method Dispatch:
It is the mechanism by which the call to an overriding method is resolved at runtime, not at compile time.
Allows the implementation of polymorphism in Java.
How It Works:
A superclass reference variable can reference a subclass object.
When an overridden method is called through a superclass reference, the version of the method to be executed is determined based on the type of the object at the time of the call.
Therefore, the choice of the method to be executed occurs at run time.
Importance:
The type of the referenced object (not the type of the reference variable) determines which version of the overridden method will be executed.
This allows different types of objects, referenced by a superclass reference variable, to call different versions of the overridden method.
Program Structure:
Superclass: Sup, with the who() method.
Subclasses: Sub1 and Sub2, both override the who() method.
Execution in main():
Creation of objects superOb (type Sup), subOb1 (type Sub1), and subOb2 (type Sub2).
A reference variable supRef of type Sup is used to reference the different objects.
Behavior:
Program output:
Depending on the type of the referenced object (superOb, subOb1, or subOb2), the corresponding version of the who() method is called and displayed.
This demonstrates the concept of dynamic dispatch, where the method executed is decided at runtime, allowing the implementation of polymorphism.
The above is the detailed content of Overlapping methods support polymorphism. For more information, please follow other related articles on the PHP Chinese website!