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
Barbara StreisandOriginal
2024-12-18 21:23:11894browse

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();
}

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");
    }
}
public class Female extends Human {
    ...
    @Override // Annotation indicating override
    public void goPee() {
        System.out.println("Sit Down");
    }
}

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();
}

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:
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