package ploymorphism;
public class AnimalDemo {
public static void main(String[] args) {
//父类的引用变量可以引用其子类对象
Animal ani1= new Dog("旺旺"); //向上转型
//向上转型是安全的,但可能会导致子类方法的丢失
//父类的引用变量只能调用父类中有的方法或子类重写的方法
ani1.eat();
//ani1.sleep(); The method sleep() is undefined for the type Animal
Animal ani2 = new Cat("招福猫");
ani2.eat();
//向下转型是不安全的
//Cat cat=(Cat)ani1; java.lang.ClassCastException
if (ani2 instanceof Cat){
System.out.println("注意身体");
Cat cat=(Cat)ani2;
cat.sleep();
}
}
}
class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
// 这是一个通用方法,由子类去实现
public void eat() {
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
// 对父类的方法进行重写
public void eat() {
System.out.println("爱吃骨头的汪");
}
public void sleep() {
System.out.println("爱睡懒觉的汪");
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
// 对父类的方法进行重写
public void eat() {
System.out.println("爱吃罐头的喵");
}
public void sleep() {
System.out.println("爱睡懒觉的猫唔");
}
}