How to achieve polymorphism in Java?
In Java, implementing polymorphism requires satisfying the following conditions:
- There is an inheritance relationship: subclasses inherit from parent classes or implement interfaces.
- Override method: Subclass overrides methods in parent class (or interface).
- The reference of the parent class (or interface) points to an object of the subclass.
Here is an example code demonstrating polymorphism.
// 定义一个父类
class Animal {
public void sound() {
System.out.println("动物发出声音");
}
}
// 定义两个子类,分别继承父类
class Cat extends Animal {
@Override
public void sound() {
System.out.println("猫发出喵喵的声音");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("狗发出汪汪的声音");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
// 父类类型的引用指向子类的对象
Animal animal1 = new Cat();
Animal animal2 = new Dog();
// 调用方法,实现多态
animal1.sound(); // 输出:猫发出喵喵的声音
animal2.sound(); // 输出:狗发出汪汪的声音
}
}
In the above example code, Animal is the superclass, and Cat and Dog are subclasses of Animal. By using Animal type references to point to objects of Cat and Dog, polymorphism is achieved. When calling the sound() method, because the Animal type reference points to the actual object type, the corresponding subclass sound() method will be automatically called. The output will vary depending on the actual object type, demonstrating the characteristics of polymorphism.