• 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
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

I don't understand why

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
interface I{}
class Q1{}

public class Q2{
public static void main(String arg[]){
Q2 q2 = new Q2();
I i = (I) q2; //compile fine. Why? test doesn't implement I and compiler known about this
Q1 q1 = (Q1) q2; //this line will fail compile, because Q1 doesn't superclass for Q2 And this is right
}
}
---------------
I i = (I) q2 //Runtime Exception
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A cast to an interface is always allowed at compile-time unless the class is final.

The idea is that even if the class does not implement the interface, a subclass might.

However, if the class is final, it can't have a subclass.

At runtime you will get a ClassCastException.
 
Vladimir Scheglov
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic