How is polymorphism implemented in Java?

Polymorphism in Java is achieved through inheritance and method overriding.

Firstly, a parent class needs to be defined, which includes one or more methods.

Next, define one or more subclasses that inherit from the parent class and override the methods in the parent class.

Abstract methods in the parent class can be defined using the keyword ‘abstract’, so subclasses must implement these abstract methods.

When using polymorphism, a variable of the parent class type can be declared to reference a child class object, and methods can be called through this variable. Therefore, based on the actual type of the referenced child class object, overridden methods in the child class can be called.

Here is a sample code:

class Animal {
    public void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    public void sound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    public void sound() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();
        
        animal1.sound(); // 输出:"Dog barks"
        animal2.sound(); // 输出:"Cat meows"
    }
}

In the above code, Animal is the parent class, and Dog and Cat are the child classes. The Animal class defines a sound() method, which is then overridden by the Dog and Cat classes respectively.

In the main() method, animal1 and animal2 are variables of type Animal that respectively reference objects of the Dog and Cat classes. When the sound() method is called using these variables, it actually invokes the overridden method in the subclass, rather than the method in the parent class. This is the effect of polymorphism.

bannerAds