• Post Reply Bookmark Topic Watch Topic
  • New Topic

ClassCastException  RSS feed

 
Tarun Oohri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everybody
I am not able to understand why does the following code throws ClassCastException : Thanks!!!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well...why do you think it should throw an exception?

 
sai rama krishna
Ranch Hand
Posts: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Foo is interface.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That doesn't make any difference.
Write down the types of all the objects you have, and list all their superclasses and implemented interfaces.
 
Arthur Vinicius Rebelo
Ranch Hand
Posts: 30
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...why does the following code throws ClassCastException

Before the assignment comes the cast. Also take a look what is the runtime type of x.
 
salvin francis
Bartender
Posts: 1649
37
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The exception itself says it all :

Exception in thread "main" java.lang.ClassCastException: Beta cannot be cast to Delta


 
salvin francis
Bartender
Posts: 1649
37
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More simplified version of your program (It still throws the same exception)



Even more simplified:


 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few things you need to understand about inheritance and casting.

Inheritance means specialization: when Beta extends Alpha, it means that Beta is a special kind of Alpha. Note that a Beta is an Alpha, just a specific kind of Alpha. This means that anything that you can do with an Alpha, you can also do with a Beta. (This is called the Liskov substitution principle).

Casting means that you are telling the compiler: I have an object here, and I want you to treat it as if it is of type X. Note that casting does not convert the object automatically to type X. It is only to tell the compiler that you know better than the compiler what type it is. A type check will still be done, but at runtime instead of at compile time. If at runtime it is found that the object is not of type X, you will get a ClassCastException.

Then, let's look at your example. Let's first use more concrete names than Alpha, Beta and Delta, to make it more clear.

Note that x refers to a Bovine. In line 9, we try to cast it to Cow. This is wrong, because x is a Bovine, not a Cow. Note that all cows are bovines, but not all bovines are cows! So you cannot in general treat any bovine as if it is a cow.

Line 11 is perfectly fine. You cast x to Animal - ok, because x is a Bovine, which is an Animal. Then you cast it to Bovine, which is also ok, because it is indeed a Bovine.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Maybe you thought that casting changes the runtime type of an object. It doesn't. Casting merely suggests to the compiler that it can treat a reference declared as one type as if it were really some other type. It's a way for the programmer to tell the compiler: "Don't worry, I know this code may look like it violates some of your type checking rules but I assure you that this object can be treated as if it were that other type" With that assurance, the compiler will relax its type-checking rules and allow your code to compile. The runtime system is not as lenient. It knows what the actual type of the object is. If you try to "trick" it, it will complain.

I've changed the names in your code so it's easier to relate. On line 8, x references a new Brass instrument object. The object referenced by x at that point is neither a Trumpet nor a Horn; the actual type at runtime is simply a generic Brass instrument. The compiler will accept the code but when line 10 is executed, the runtime system cannot be coerced into treating a Brass instrument as a Trumpet because the object isn't really a Trumpet.

On the other hand, line 13 declares variable y as a reference to a Brass instrument. The actual object that it references is a Trumpet, so line 14 works at runtime. On line 15, we tell Java to treat the object referenced by f (declared as an Instrument) as a Trumpet. The compiler is appeased by the cast and the runtime system allows it because the object being referenced really is a Trumpet.

On line 17, we reassign f so that it now references a Horn object. On line 18, we again tell Java that f is as Trumpet. Again, the compiler will take our word for it. However, this time the runtime system will not allow it because the object that f references at this point is actually a Horn, not a Trumpet.

 
sai rama krishna
Ranch Hand
Posts: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Wind implements Instrument {}
class Brass extends Wind {}
class Trumpet extends Brass {}
class Horn extends Brass {}


interface Animal {}
class Mammal implements Animal { }
class Bovine extends Mammal {}

class Cow extends Bovine {




English is my second language. I wonder how Bovine is related to Cow. Are both same. Also how Trumpet is related to Brass( is it a metal? or instrument). Also how Horn(i only know one horn which is Animal has horns) is related to Instrument. Also Wind means Air right not any kind of instrument? Please advise
 
Tarun Oohri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you everybody for making me understand ... I really apritiate your help...but I could not understand one thing ...
class A{}
class B extends A{}
class C extends B{
public static void main(String...s){
C c = (new C())(new B())new C();
}
}
Here we are first casting c into b...which is OK.. Now at this stage ..the object is of b...ie.
C c = (new C())b; where b refers to B object.
Now how can we cast B into C ???
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tarun Oohri wrote:...but I could not understand one thing ...
class A{}
class B extends A{}
class C extends B{
public static void main(String...s){
C c = (new C())(new B())new C();
}
}
Here we are first casting c into b...which is OK.. Now at this stage ..the object is of b...ie.
C c = (new C())b; where b refers to B object.
Now how can we cast B into C ???


To be blunt, if you are going to use Java code as examples, wouldn't it be a good idea to show code that actually compiles??

Henry
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sai rama krishna wrote:
English is my second language. I wonder how Bovine is related to Cow. Are both same. Also how Trumpet is related to Brass( is it a metal? or instrument). Also how Horn(i only know one horn which is Animal has horns) is related to Instrument. Also Wind means Air right not any kind of instrument? Please advise


Basically, one is a specialization of the other. In other words, a Bovine IS-A Cow, but a Cow is not necessarily a Bovine.

On the other hand, I don't have a strong opinion regarding this. If it makes sense, great. And if it does not make sense, it is you who have to defend it during a code review with your colleagues. It would probably be a good idea to have a set of rules that works for you, and is defensible...

Henry
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote: a Bovine IS-A Cow, but a Cow is not necessarily a Bovine.

Actually, a Cow IS a Bovine. Not all Bovines are Cows though. Some Bovines are Buffalo.

Also, for the rancher who doesn't know much about classifications of animals or musical instruments, I suggest you hit Wikipedia for that.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:
Henry Wong wrote: a Bovine IS-A Cow, but a Cow is not necessarily a Bovine.

Actually, a Cow IS a Bovine. Not all Bovines are Cows though. Some Bovines are Buffalo.


Sorry. Read the attached code backwards... have a cow ...

Henry
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Sorry. Read the attached code backwards... have a cow ...

Oh Ok, I see what you did there...
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote: . . . a Bovine IS-A Cow, but a Cow is not necessarily a Bovine. . . .
Are you sure it is that way round? I thought it was the other way round.

Let's get back to the instruments.
  • Instruments: Musical Instruments images
  • Wind Instruments: Wind Instruments images
  • Brass Instruments: Brass Musical Instruments images
  • Trumpets: Trumpet images
  • you should find a trumpet in each of those sets of images.
    If you go back you will find a trumpet IS‑A brass instrument and a brass instrument IS‑A wind instrument and a wind instrument IS‑A musical instrument.

    The Wikipedia pages about classification of musical instruments is positively misleading and inaccurate.
     
    Campbell Ritchie
    Marshal
    Posts: 56525
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The musical instrument called a horn probably had its origins in blowing animals' horns, but it now looks like this: Musical Instrument images Horns One of those pictures shows a Serpent, which is not actually a horn at all. It is a kind of oboe.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!