• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

casting problem

 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
given the code:
class X{}
class A extends X implements T{
public void foo(){
System.out.println("it works");
}
}
class B extends A{}
interface T{void foo();}
class BB{}
....
BB bb=new BB()
//T t=(T)bb;// runtime exception is OK -case A
B b=new B();// Case B
t=(T)b;
In case A the program gives a runtime exception no problem since object pointed by bb does not implement T
I think it should also give a runtime exception in Case B the object to which b points also does not implement interface T.
I do not understand why the program runs in this case.
I think the fact that class A which is a superclass of B and implements T
CANNOT be the explanation because.
JLS 2.0 states that the class itself must implement the interface
Can someone give me some input on this...
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dan,
Your understanding is correct the code compiles because the parent class of B has already implemented the interface T.
Now think of this all public members of class A are members of class B so from the point of class B it really doesn't matter if the parent class has implemented the method as long as class B is aware of the method.
hope this helps.
-S
 
Dan Andrei
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I used the same reasoning as you regarding the inheritance BUT
I thought the implements clause is mandatory, but it seems is not I just try an example and it compiles fine
reply
    Bookmark Topic Watch Topic
  • New Topic