"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Overlapping methods support polymorphism

Overlapping methods support polymorphism

Published on 2024-11-07
Browse:121

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.

Métodos sobrepostos dão suporte ao polimorfismo

Métodos sobrepostos dão suporte ao polimorfismo

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:

  • The call to supRef.who() determines the version of the method to be executed based on the type of the object referenced at the time of the call, not the type of the reference variable supRef.

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.

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/metodos-sobrepostos-dao-suporte-ao-polimorfismo-457j?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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