public void eat() { //重写父类方法
System.out.println("吃鱼");
}
public void catchMouse() { //猫的特有功能
System.out.println("抓老鼠");
}
}
//定义一个狗类继承动物类
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
public void kanJia() { //狗的特有功能
System.out.println("看家");
}
}
//定义一个猪类继承动物类
class Pig extends Animal {
public void eat() {
System.out.println("吃饲料");
}
public void gongDi() { //猪的特有功能
System.out.println("拱地");
}
}
//运行类
class ZhuanXingDemo {
public static void main(String[] args) {
Animal c = new Cat();
Animal d = new Dog();
Animal p = new Pig();
funEat(c);
funEat(d);
funEat(p);
}
//写一个函数可以输出子类调用父类的函数内容
public static void funEat(Animal a) { //Animal a = new Cat(Dog, Pig)();
a.eat();
if(a instanceof Cat) { //如果传进来的数据属于猫类型。就通过关键字instanceof判断
Cat c = (Cat)a;
c.catchMouse();
} else if(a instanceof Dog) { //如果传进来的数据属于狗类型。就通过关键字instanceof判断
Dog g = (Dog)a;
g.kanJia();
} else if(a instanceof Pig) {
Pig p = (Pig)a;
p.gongDi();
}