permaculture playing cards*
The moose likes Beginning Java and the fly likes Why this exception ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why this exception ?" Watch "Why this exception ?" New topic
Author

Why this exception ?

Neha Mohit
Ranch Hand

Joined: Apr 25, 2006
Posts: 87
Hello all,

Why does this code on execution gives ClassCastException though the elements of Fruit is of type Apple


class Fruit{ }
class Apple extends Fruit{ }



class Test
{
public static void main(String[] args)
{
Fruit[] a=new Fruit[]{new Apple(),new Apple()};
Apple[] d=(Apple[])a;
}

}

Thanks in advance
[ April 29, 2006: Message edited by: Neha Mohit ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
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.

Anybody better able to explain than me, please do

CR
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Actually...

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:

Fruit[] a=new Apple[]{new Apple(),new Apple()};
Apple[] d=(Apple[])a;


[Jess in Action][AskingGoodQuestions]
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
I was mistaken, wasn't I?

Sorry
Neha Mohit
Ranch Hand

Joined: Apr 25, 2006
Posts: 87
Thanks to all of you.
 
Consider Paul's rocket mass heater.
 
subject: Why this exception ?
 
Similar Threads
Polymorphic calls
another instanceof question
query regarding exception
Object referernce casting
Why declare an object and instantiate it as instance of inherited type?