public class Test_diversifyTest1 {
public static void main(String[] args){
Cycle c = new Cycle();
print(" 车轮数:"+c.ride(neum.Bicycle).wh);
Unicycle c1 = new Unicycle();
print(" 车轮数:"+((Unicycle)c1.ride(neum.Unicycle)).wh);
print(" 车轮数:"+((Unicycle)c1.ride(neum.Unicycle)).wh1);
// 依然有疑问,按照程序的执行来看得到的返回类型是Cycle,但是为什么是Cycle还是不是很了解,但是正确的做法就是这样
// 把返回的Cycle类型强制转换成Unicycle类型就能得到正确的wh了
// 向下面这样子会得到的结果是0而不是4,因为遵循就近原则,哪儿近就得到哪儿的
// print(" 车轮数:"+c1.ride(neum.Unicycle).wh);
}
}
class Cycle{
int wh = 0;
public Cycle(){
print("This is in The class Cycle!");
}
public Cycle ride(Object o){
print("Class: "+ this);
return this;
}
}
class Unicycle extends Cycle{
int wh1 = 4;
public Unicycle(){
print("This is in The class Unicycle!");
}
public Unicycle ride(Unicycle o){
print("Class: "+ this);
return this;
}
}
class Bicycle extends Cycle{
int wh = 2;
public Bicycle(){
print("This is in The class Bicycle!");
}
}
class Tricycle extends Cycle{
int wh = 3;
public Tricycle(){
print("This is in The Tricycle!");
}
}
//Output:
//This is in The class Cycle!
//Class: Diversify.Cycle@61de33
// 车轮数:0
//This is in The class Cycle!
//This is in The class Unicycle!
//Class: Diversify.Unicycle@ca0b6
// 车轮数:0
//Class: Diversify.Unicycle@ca0b6
// 车轮数:4