多态的向上转型
时间: 2023-07-19 12:15:15 浏览: 49
多态的向上转型是指将一个子类类型的对象赋值给父类类型的引用变量,从而使得这个引用变量既可以引用父类对象,也可以引用子类对象,实现了代码的灵活性和可扩展性。向上转型可以通过自动类型转换来完成,例如:
```
class Animal {
public void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dog is eating.");
}
public void bark() {
System.out.println("Dog is barking.");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Dog(); // 向上转型
animal.eat(); // 执行的是 Dog 类的 eat 方法
// animal.bark(); // 错误,Animal 类型没有 bark 方法
}
}
```
在上面的例子中,Dog 类继承自 Animal 类,Animal 类型的引用变量 animal 可以指向 Dog 类型的对象,这就是向上转型的效果。虽然 animal 引用变量被声明为 Animal 类型,但是在运行时会动态地调用 Dog 类的 eat 方法。但是 animal 引用变量不能调用 Dog 类特有的方法 bark。