一、多态
- 父类引用指向不同的子类对象,调用同一个方法时,表现出不同的行为,这就叫多态。
- 需要有向上转型的操作。
例:Animal(父类) animal = new Dog(子类)("小黄", 10); - 子类必须重写父类的该方法。
- 必须有继承关系。
二、向上转换场景
2.1 直接赋值
例:Animal a = new Dog(); // 父类引用指向子类对象
a.eat(); // 调用 Dog 类重写的 eat 方法
2.2 方法传参
例:public void feed(Animal a) { // 参数声明为父类类型
a.eat();
}
// 调用时传不同子类
feed(new Dog()); // 狗吃骨头
feed(new Cat()); // 猫吃鱼
2.3 方法返回
例:public Animal getAnimal(String type) {
if ("dog".equals(type)) {
return new Dog(); // 返回子类对象,但声明为父类
} else if ("cat".equals(type)) {
return new Cat();
}
return null;
}
Animal a = getAnimal("dog"); // 实际拿到 Dog,但用 Animal 接
a.eat();
2.4 优点与缺点
- 优点:代码实现更简单灵活。
- 缺点:不能调用到子类特有方法。
三、向下转型
3.1 父类类型给到子类
例:Dog dog(子类) = (Dog) animal(父类);
3.2 instanceof
使用时加个判断:if (animal instanceof Dog) {}
instanceof:animal 是不是 Dog 的实例(两侧的类必须有父子继承关系)。
3.3 缺点
存在类型转换风险,可能导致 ClassCastException 异常。