天天看點

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{

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

    void fight() {

        System.out.println("我是藏獒,我愛戰鬥");

class Hasiq extends Dog{

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

    void play() {

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

繼續閱讀