Home > Java > javaTutorial > How Does Polymorphism Work in Java Through Inheritance and Method Overriding?

How Does Polymorphism Work in Java Through Inheritance and Method Overriding?

Barbara Streisand
Release: 2024-12-18 21:23:11
Original
952 people have browsed it

How Does Polymorphism Work in Java Through Inheritance and Method Overriding?

Polymorphism, Overriding, and Overloading in Java

Defining Polymorphism

When discussing polymorphism in Java, neither overloading nor overriding fully encapsulate its essence. Polymorphism is best understood through abstract base classes or interfaces.

Abstract Base Classes and Polymorphism

Consider an abstract base class Human with an abstract method goPee(), defining a concept that isn't fully realizable for humans until instantiated in its subclasses, such as Male and Female.

public abstract class Human {
    ...
    public abstract void goPee();
}
Copy after login

Overriding in Subclasses

Subclasses like Male and Female implement the goPee() method based on their specific characteristics:

public class Male extends Human {
    ...
    @Override // Annotation indicating override
    public void goPee() {
        System.out.println("Stand Up");
    }
}
Copy after login
public class Female extends Human {
    ...
    @Override // Annotation indicating override
    public void goPee() {
        System.out.println("Sit Down");
    }
}
Copy after login

Polymorphic Behavior

With this setup, an array of Human objects can contain both Male and Female instances. When calling goPee() on all humans, the overridden method specific to each subclass is executed, showcasing polymorphic behavior:

public static void main(String[] args) {
    ArrayList<Human> group = new ArrayList<>();
    group.add(new Male());
    group.add(new Female());

    // Polymorphism: Execute overridden goPee() in each subclass
    for (Human person : group) person.goPee();
}
Copy after login

Conclusion

Polymorphism manifests through the ability of objects of different classes to respond differently to the same method call. It leverages inheritance and method overriding to achieve this flexibility.

The above is the detailed content of How Does Polymorphism Work in Java Through Inheritance and Method Overriding?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template