I've been learning about inheritance in Java and am not certain if you can cast a Parent object into a Child object. I would have thought that was okay (but the other way around was a no-no), but after reading up on the topic, I think that this cannot be done. I'd like to ask the forum if I am correct.
Suppose I have a program called FruitCart which works with a lot of class Fruit objects:
public class Fruit{
String color;
boolean hasSeeds;
public Fruit(String a, boolean b){
this.color = a;
this.hasSeeds = b;
}
}
public class FruitCart{
public static void main(String[] args){
Fruit fruitA = new Fruit("red", true);
Fruit fruitB = new Fruit("yellow", false);
...many more...
}
}
Okay. Now suppose that as my program continues, it learns more properties about the fruit in the cart. For example, maybe my program learns that fruitA is of type "Red Delicious." We now know that fruitA is an apple, and it would be great to convert fruitA from an instance of class Fruit to an instance of class Apple:
public class Apple extends Fruit{
String type;
public Apple(String a, boolean b, String c){
super(a, b);
this.type = c;
}
}
My question is... is it impossible to cast fruitA from a Fruit to an Apple object?
public class FruitCart{
public static void main(String[] args){
Fruit fruitA = new Fruit("red", true);
fruitA = new Apple(, "Red Delicious"); // nope
...or...
fruitA = (Apple)fruitA; // no good
...or...
Apple appleA = (Apple)fruitA; // nada
}
}
I've been Googling for this for over an hour, and as I said, I think that the answer is no. This post alone made me think so:
Casting in Java(interface and class)
However, I am not experienced enough to know if the materials I'm reading directly correlate to the issue I'm describing here. Can folks here confirm?
Many thanks, -RAO