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();
}
}
I expect the result to be:
Calling method from Car: the color is Red
Calling method from BMW: the color is Black
Calling method from Car: the color is Black
But, the result I got is:
Calling method from Car: the color is Red
Calling method from BMW: the color is Black
Calling method from BMW: the color is Black
Where am I wrong?
And how can I use the method from the super class to get the data in a subclass object?
I can write a toCar() method in BMW class to do this.
But, why casting doesn’t work?
Thanks ahead!
OK! Thank you!
I got why casting doesn’t work.
So, I add a method in BMW toCar() to get the result I want.
Casting the object does not change the nature of the object. It is still a BMW object; casting just tells the compiler to treat it as though it were a Car object.
As long as we’re on the subject of inheritance: there is NO need to put either the color variable or the get/setColor methods into both the super and subclass. Putting them in the car class means they are available in any subclass; they are superfluous and a bit confusing in the subclass. I would take them out entirely.