package test;
abstract class Animal {
abstract void eat();
}
class Dog extends Animal {
void eat() {
System.out.println("eat bone");
}
void guardHome() {
System.out.println("guard home");
}
}
class Cat extends Animal {
void eat() {
System.out.println("eat fish");
}
void catchMouse() {
System.out.println("catch mouse");
}
}
public class AnimalDemo {
public static void main(String[] args) {
Animal a = new Cat();
function(a);
a = new Dog();
function(a);
}
public static void function(Animal a) {
a.eat();
if(a instanceof Cat) { //判断所属类型
((Cat) a).catchMouse(); // 对象a的类型为Animal,这里向上转型 转成Cat
}else if(a instanceof Dog) { //判断所属类型
((Dog) a).guardHome(); // 对象a的类型为Animal,这里向上转型 转成Dog
}
System.out.println();
}
}