• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Q> ClassCastException for not implementing the specific interface?

 
Winston Liek
Ranch Hand
Posts: 173
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the following code compiles? This question was taken from Mala Gupta's twist in the tale book:



I was expecting that it will not be compiled because blackInk does not implement class Printable yet it was assigned to it printable = (Printable)blackInk;?

 
Andrea Black
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm a newbie myself, but what I think is that the compiler lets us cast between compatible data types. It cannot know that this casting is wrong. The error is then caught at runtime. Hence ClassCastException happens at runtime.
 
Roel De Nijs
Sheriff
Posts: 10429
133
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Liek wrote:Why does the following code compiles?

Short explanation: The code compiles because BlackInk is a non-final class.

Long explanation:
Because the BlackInk class is not final, I can create a subclass of BlackInk which implements Printable, like this:


And then I can create an instance of LightBlackInk which I can cast (without any problem) to the Printable interface. Shown in this example:


The short explanation should make you think about what would happen if BlackInk would be marked as final The answer and the same (but even longer) explanation can be found in this thread.

Hope it helps!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic