黑马程序员-多态的使用,基类和导出类中方法、属性的使用

---------------------- android培训java培训、期待与您交流! ----------------------


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


-------------------- android培训java培训、期待与您交流! ----------------------

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值