How can polymorphism be achieved in Java?

In Java, there are several ways to implement polymorphism.

  1. Subclasses can override methods of the parent class by inheritance and method overriding, so that when the method is called through a reference to the parent class, the subclass’s overridden method will be executed instead.
  2. Polymorphism is achieved through interfaces, which define a set of method specifications. Classes that implement the interface can then implement these methods based on their own needs. When methods are called through an interface reference, the corresponding method in the implementing class is actually executed.
  3. To achieve this through method overloading, multiple methods are defined in the same class with the same name but different parameter lists. When calling the method, the specific method to call is determined based on the type and number of parameters passed in.

Below is an example code:

class Animal {
    public void sound() {
        System.out.println("动物发出声音");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("狗叫");
    }
}

class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("猫叫");
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();
        animal1.sound();
        animal2.sound();
    }
}

Output result:

狗叫
猫叫

In the example above, the Animal class is the parent class, and the Dog and Cat classes are the child classes. They both override the sound() method of the parent class. When the sound() method is called through a parent class reference, the actual method executed is the one overridden by the child class. This is an example of polymorphism.

bannerAds