- class TestAnimal {
- public static void main(String[] args) {
- //Animal a = new Cat(); //创建父类引用,子类对象
- //a.eat(); //调用吃饭
- getAnimal(new Dog()); //传递狗类参数
- getAnimal(new Cat()); //传递猫类参数
- }
- public static void getAnimal(Animal a) {//
- if (a instanceof Cat) {
- Cat c = (Cat)a;
- c.eat();
- c.catchMouse();
- } else if (a instanceof Dog) {
- Dog d = (Dog)a;
- d.eat();
- d.lookHome();
- }
- }
- }
- /*案例演示:
- 具体事务:猫,狗
- 共性:姓名,年龄,吃饭
- 猫的特性:抓老鼠
- 狗的特性:看家*/
- abstract class Animal { //动物抽象类
- String name; //名字
- int age; //年龄
- abstract public void eat(); //抽象方法吃饭
- }
- class Cat extends Animal { //猫类,继承动物类
- public void eat() { //重写抽象方法吃饭
- System.out.println("猫吃鱼");
- }
- public void catchMouse() { //抓老鼠
- System.out.println("抓老鼠");
- }
- }
- class Dog extends Animal { //狗类,继承动物类
- public void eat() { //重写抽象方法吃饭
- System.out.println("狗吃肉");
- }
- public void lookHome() { //看家
- System.out.println("看家");
- }
- }
复制代码 |
|