Method Override:
It is 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:
Is the mechanism by which the call to an overlapping method is resolved at run time, 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 supRef reference variable 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3