Home > Java > javaTutorial > Overlapping methods support polymorphism

Overlapping methods support polymorphism

DDD
Release: 2024-09-18 22:53:53
Original
646 people have browsed it

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.

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 reference variable supRef 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.

The above is the detailed content of Overlapping methods support polymorphism. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template