java子类强制转换,关于在JAVA中将子类强制转换为超类

public class Car {

String color;

public void thisIs(){

System.out.println("Calling method from Car: the color is " + color);

}

public String getColor() {

return color;

}

public void setColor(String color) {

this.color = color;

}

}

public class BMW extends Car {

public void thisIs(){

System.out.println("Calling method from BMW: the color is " + color);

}

public Car toCar(){

Car newCar = new Car();

newCar.setColor(this.color);

return newCar;

}

}

public class AbstractTest {

public static void main(String args[]){

Car aCar = new Car();

aCar.setColor("Red");

aCar.thisIs();

BMW aBMW = new BMW();

aBMW.setColor("Black");

aBMW.thisIs();

//Car aaCar = new Car();

//aaCar = (Car)aBMW;

//aaCar.thisIs();

Car aaCar = aBMW.toCar();

aaCar.thisIs();

}

}

我希望结果如下:

Calling method from Car: the color is Red

Calling method from BMW: the color is Black

Calling method from Car: the color is Black

但是,我得到的结果是:

Calling method from Car: the color is Red

Calling method from BMW: the color is Black

Calling method from BMW: the color is Black

我哪里错了?

如何使用超类中的方法获取子类对象中的数据?

我可以在BMW类中编写一个toCar()方法来执行此操作.

但是,为什么铸造不起作用?

谢谢!

好!谢谢!

我知道为什么铸造不起作用.

所以,我在BMW toCar()中添加了一个方法来获得我想要的结果.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值