Parrot向Swallow?不可能,肯定会提示classcastexception

解决方案 »

  1.   

    Adapter的基本思想是:public class SwallowParrot extends Swallow {
      private Parrot parrot;
      
      public void eat () {
        super.eat();
        parrot.eat();
      }
    }但是,你用公共接口用定义这些会更方便:
    public interface BirdIF {
      void fly();
      void eat();
    }public interface SwallowIF extends BirdIF {
      void swim();
    }public interface ParrotIF extends BirdIF {
      void jump();
    }public class ParrotAndSwallow implments BirdIF, SwallowIF, ParrotIF {}test() {
      ParrotAndSwallow hybrid = new ParrotAndSwallow();
      BirdIF asBird = (BirdIF) hybrid;
      ParrotIF asParrot = (ParrotIF) hybrid;
      SwallowIF asSwallow = (SwallowIF) hybrid;
    }