How can polymorphism be achieved in Java?

In Java, polymorphism is achieved through inheritance and method overriding. The specific steps are as follows:

  1. Create a base class with one or more methods, ensuring that at least one method is overridden by a subclass.
public class Animal {
    public void sound() {
        System.out.println("动物发出声音");
    }
}
  1. Create one or more subclasses by inheriting from a base class and overriding its methods.
public class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("猫发出“喵喵”的声音");
    }
}

public class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("狗发出“汪汪”的声音");
    }
}
  1. Creating objects and invoking methods: Achieve polymorphism by creating base class objects or subclass objects and calling methods.
public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Animal();
        Animal animal2 = new Cat();
        Animal animal3 = new Dog();

        animal1.sound(); // 动物发出声音
        animal2.sound(); // 猫发出“喵喵”的声音
        animal3.sound(); // 狗发出“汪汪”的声音
    }
}

In the above code, three objects, animal1, animal2, and animal3, were created using the base class Animal, and the sound() method was called on each object. Animal1 called the method of the base class, while animal2 and animal3 called the overridden methods of the subclasses Cat and Dog, thus achieving polymorphism.

bannerAds