• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this exception ?

 
Neha Mohit
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49827
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Campbell Ritchie
Sheriff
Pie
Posts: 49827
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was mistaken, wasn't I?

Sorry
 
Neha Mohit
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all of you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic