A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

package Diversify;
//关于多态,多方求解之后方得到正确答案
import static Test_purview.print.*;
import Test_initalized.neum;

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

评分

参与人数 1黑马币 +10 收起 理由
职业规划-刘倩老师 + 10 赞一个!

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马