在Java中,父类的变量可以引用父类的实例,也可以引用子类的实例。请读者先看一段代码:
public class Demo {
public static void main(String[] args){
Animal obj = new Animal();
obj.cry();
obj = new Cat();
obj.cry();
obj = new Dog();
obj.cry();
}
}
class Animal{
// 动物的叫声
public void cry(){
System.out.println("不知道怎么叫");
}
}
class Cat extends Animal{
// 猫的叫声
public void cry(){
System.out.println("喵喵~");
}
}
class Dog extends Animal{
// 狗的叫声
public void cry(){
System.out.println("汪汪~");
}
}
运行结果:
上面的代码,定义了三个类,分别是 Animal、Cat 和 Dog,Cat 和 Dog 类都继承自 Animal 类。obj 变量的类型为 Animal,它既可以指向 Animal 类的实例,也可以指向 Cat 和 Dog 类的实例,这