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