aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Mongo DB Applied Patterns this week in the MongoDB forum
or a resume review from Five Year Itch in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "casting problem" Watch "casting problem" New topic
Author

casting problem

Dan Andrei
Ranch Hand

Joined: Jan 21, 2004
Posts: 92
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...


"Did anyone understand what I have just explained? ... because I did not!"
Sudhakar Krishnamurthy
Ranch Hand

Joined: Jun 02, 2003
Posts: 76
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

Joined: Jan 21, 2004
Posts: 92
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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: casting problem
 
Similar Threads
Regarding Casting between classes and interface
Simple J2SE 5.0 Tiger Notes
Casting Doubt