This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Associate Certification (OCAJP 7) and the fly likes Q> ClassCastException for not implementing the specific interface? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Associate Certification (OCAJP 7)
Bookmark "Q> ClassCastException for not implementing the specific interface?" Watch "Q> ClassCastException for not implementing the specific interface?" New topic
Author

Q> ClassCastException for not implementing the specific interface?

Winston Liek
Ranch Hand

Joined: Jan 19, 2014
Posts: 61
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

Joined: Feb 26, 2014
Posts: 39
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
Bartender

Joined: Jul 19, 2004
Posts: 5122
    
  12

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!


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Q> ClassCastException for not implementing the specific interface?
 
Similar Threads
Accessing an object using a reference variable of an unrelated Interface
Question #1 from Doug's book
inheritance
interface extending a an abstract class
casting