instance与可变参数合用,多态性

public class Doubt {

    public static void main(String[] args) {

        Dog d1=new Dog();

        Dog d2=new Zangao();

        Dog d3=new Hasiq();

        Master m=new Master();

        m.feed(d1,d2,d3);

    }

}

class Master {

    void feed(Dog ... d1) {

        for(Dog d:d1) {

            d.eat();

            if(d instanceof Zangao) {

                Zangao z=(Zangao)d;

                z.fight();

                System.out.println("是藏獒");

            }

            if(d instanceof Hasiq) {

                Hasiq h=(Hasiq)d;

                h.play();

                System.out.println("是哈士奇");

            }

        }

    }

}

class Dog {

    void eat() {

        System.out.println("狗吃东西");

    }

}

class Zangao extends Dog{

    void eat() {

        System.out.println("藏獒吃东西");

    }

    void fight() {

        System.out.println("我是藏獒,我爱战斗");

    }

}

class Hasiq extends Dog{

    void eat() {

        System.out.println("哈士奇吃东西");

    }

    void play() {

        System.out.println("我是哈士奇,我爱玩耍");

    }

}

原文地址:https://www.cnblogs.com/u0mo5/p/4149089.html