Hello. What you are doing is nothing to do with the fact that Apple is a subclass of Fruit. there is no way you can make Apple a subclass of Fruit. Remember that an array is an object in its own right, and has its own type, but you can't set one array to be an array of a different type.
Apple is a subclass of Fruit! That's how arrays work in Java.
But here you haven't created an Apple object; you created a Fruit object with Apple objects in it. Apple and Fruit are two different classes with different capabilities; for example, a Fruit can hold Pear and Orange objects, while an Apple can not. A cast can never change the actual class of an object; it can only tell the compiler something about the true type that it doesn't realize.
If we do actually create an Apple, then your program works fine:
You can't cast an array who's runtime type is Fruit to an Apple because there is no guarantee that the array contains only Apple objects. Consider this example where there is more than one subclass of Fruit.
However if the runtime type is an Apple then the compiler can enforce that there are only apples stored in the array:
However this is ok:
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Joined: Oct 13, 2005
I was mistaken, wasn't I?
Joined: Apr 25, 2006
Thanks to all of you.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com