Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Q> ClassCastException for not implementing the specific interface?

 
Ranch Hand
Posts: 197
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;?

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic