Java 多态性示例:动物、猫和狗类的继承与重写
Java 多态性示例:动物、猫和狗类的继承与重写
本示例展示了 Java 中的多态性,通过定义动物、猫和狗类,并使用继承和重写方法实现多态调用。
动物类定义:
public class Animal {
private String name;
private int age;
private String gender;
public Animal(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public void eat() {
System.out.println(name + ' is eating.');
}
public String getName() {
return name;
}
}
猫类定义:
public class Cat extends Animal {
public Cat(String name, int age, String gender) {
super(name, age, gender);
}
@Override
public void eat() {
System.out.println(getName() + ' is eating fish.');
}
public void catchMouse() {
System.out.println(getName() + ' is catching a mouse.');
}
}
狗类定义:
public class Dog extends Animal {
public Dog(String name, int age, String gender) {
super(name, age, gender);
}
@Override
public void eat() {
System.out.println(getName() + ' is eating meat.');
}
public void watchHouse() {
System.out.println(getName() + ' is watching the house.');
}
}
测试代码:
public class Test {
public static void main(String[] args) {
Animal animal1 = new Cat("Kitty", 2, "female");
Animal animal2 = new Dog("Doge", 3, "male");
animal1.eat();
((Cat) animal1).catchMouse();
animal2.eat();
((Dog) animal2).watchHouse();
}
}
输出结果:
Kitty is eating fish.
Kitty is catching a mouse.
Doge is eating meat.
Doge is watching the house.
解释:
使用多态格式调用了动物类的 eat() 方法和子类的 catchMouse() 和 watchHouse() 方法。可以看到,虽然调用的是动物类的 eat() 方法,但实际上会根据对象的实际类型调用相应子类的 eat() 方法,这就是多态的特点。同时,由于猫类和狗类分别重写了 eat() 方法,因此它们的 eat() 方法输出的内容不同。
多态的特点:
- 同一方法,不同行为: 同一个方法
eat()在不同子类中表现出不同的行为,体现了多态的本质。 - 代码简洁灵活: 通过多态,可以使用相同的代码调用不同子类的方法,提高代码的可读性和可维护性。
- 运行时绑定: 实际调用哪个方法在运行时根据对象的实际类型决定,提高了代码的灵活性。
原文地址: https://www.cveoy.top/t/topic/okv6 著作权归作者所有。请勿转载和采集!