关于在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(); } } 

我希望结果如下:

来自Car的调用方法:颜色为红色

来自宝马的呼叫方法:颜色为黑色

来自Car的调用方法:颜色为黑色

但是,我得到的结果是:

来自Car的调用方法:颜色为红色

来自宝马的呼叫方法:颜色为黑色

来自宝马的呼叫方法:颜色为黑色

我哪里错了? 如何使用超类中的方法获取子类对象中的数据? 我可以在BMW类中编写一个toCar()方法来执行此操作。 但是,为什么铸造不起作用? 谢谢!

好! 谢谢!

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

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

投射对象不会改变对象的性质。 它仍然是宝马的对象; cast只是告诉编译器将它视为Car对象。

只要我们处于inheritance的主题:没有必要将color变量或get / setColor方法放入super和subclass中。 将它们放入汽车类意味着它们可用于任何子类; 它们是多余的,在子类中有点混乱。 我会完全把它们拿走。

即使你称之为汽车,宝马仍然是宝马。

演员阵容不会改变对象的内容。 它只是告诉编译器你打算如何对待它。 你创造了一辆宝马,当你调用它的thisIs方法时它仍然是thisIs

这是因为运行时多态性。 最后一个声明是因为即使你有一个汽车参考指向宝马对象(通过铸造你没有改变物体的性质!宝马仍然是宝马它不会成为汽车的对象!),最终它的宝马这是()方法将被调用! 这称为动态方法调度

那么你不需要explicitly cast BMW object explicitly cast到汽车类型,因为BMW objectsubclass of Car and a Car can be of any typesubclass of Car and a Car can be of any type (宝马或subclass of Car and a Car can be of any type )。 因此,当您将BMW object to a car the implicit casting is done分配给BMW object to a car the implicit casting is done由编译器BMW object to a car the implicit casting is done 。 在您的情况下,您explicitly asking the compiler to cast the BMW object to car type

此隐式转换也不意味着BMW对象将丢失其thisIs()方法或任何其他属性。

考虑以下代码:

 public void someMethod(Car c) { c.thisIs(); } 

‘c’可以保存所有子类的引用。 无论哪个引用由’c’保存,该方法都将被调用。 它也称为运行时多态。