如果我有一个包,里面有两个类:mother,baby , 其中mother有个方法getBaby() 是返回一个baby型的对象.但是我在某一个地方,有两个新的类:chinesemother,chinexebaby,完全是继承于上面那两个类,没有多任何其他东西,但是怎么解决chinesebaby cbaby =(chinesebaby) chinesemother.getBaby()的类型错误问题,是一定要从写一个getChineseBaby()的方法才行吗?

解决方案 »

  1.   

    public class Baby {
    }public class ChineseBaby extends Baby {
    }public class Mother {     Baby baby;
         
         public Mother() {
             baby = new Baby();
         }
         
         public Baby getBaby() {
             return baby;
         }
    }public class ChineseMother extends Mother {
        public ChineseMother() {
           super.baby = new ChineseBaby();
        }
    }public class Client {
        public static void main(String[] args) {
            ChineseMother mother  = new ChineseMother();
            ChineseBaby baby = (ChineseBaby)mother.getBaby();
            if( baby instanceof ChineseBaby) {
                System.out.println("chinese baby");
            } else {
                System.out.println("not chinese baby");
            }
        }
    }
      

  2.   

    class Baby {
    }class ChineseBaby extends Baby {
    }class Mother {
      Baby getBaby() { return new Baby(); }
    }class ChineseMother extends Mother {
      Baby getBaby() { return new ChineseBaby(); }
    }public class Test {
      public static void main(String[] args) {
        ChineseBaby chineseBaby = new ChineseMother().getBaby();
      }
    }
      

  3.   

    呵呵, 我只想说的是,即使你用mother也可以获得一个chinesebaby的引用呀.到时候是什么就是什么嘛.
    何必一定要...