| 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
|
 |
 |
|
|
subject: casting problem
|
|
|