is it a bug of Sun JDK ? Please help !!
Hi
I m not able to find out why following code is compiling fine. Acc to logic of OOPS, it shd not be possible.
interface A {}
class B {}
class C implements A{
public static void main(String args[]){
A a = new C();
B b = (B)a; // Here it should show inconvertible types found: A required: B
}
}
Here A is an interface and no where related to class B. So comipler shd show casting problem at compile time.
Can any one explain why this is not giving this error and compiling fine ?
--
Regards,
Ganesh Bansal
The compiler isn't searching through the entire inheritance and syntax tree. If you do a cast, it assumes you to know what you do. It only shows the most obvious cases of abuse.After all, a could contain a reference to an instance of a class D extends B implements A.
> in other words, it's a bug in your brain.
> That's in fact the case with the vast majority of
> things people think are bugs in the JDK.
That must itch like the dickens. I couldn't imagine having something crawling around in there. Must be kind hard to scratch. A sharp stick in the eye could do it though.
I have sympathy with the OP. It strikes me as unreasonable that the compiler cannot detect this obvious bad cast. BUT I'm not going to worry too much about it because it does give a ClassCastException when run.
It could only be classed as a bug if the JLS forbids it but I will let others do that research.
> I have sympathy with the OP. It strikes me as
> unreasonable that the compiler cannot detect this
> obvious bad cast.
I guess whoever wrote the compiler made a point about not trying to backtrack the latest write access to a variable to check a cast, just to see whether it is followed by a "new X" and to check whether X is legal for the cast. Unnecessary complication, especially considered that an assignment from another reference or even another cast blow that out of proportion, and totally leads to a dead end if it's the return value of some factory method or worse, Class.forName() call. The compiler will spend 3 seconds compiling and 5 minutes checking the casts.
The difference between class and interface is that a class has a defined inheritance tree. An interface hasn't, since any class with any inheritance tree of its own could implement it, and can't be checked.
If you replace
A a = new C();
with
A a = new D();
with
class D extends B implements A,
the OP's code would be very well valid and exception-free. So it would simply depend on how that reference is filled - which often cannot be traced without considerable effort, if at all.
I was just about to argue this when I saw the light by looking what would happen with the minor change to
interface A
{}
class B
{}
class C extends B implements A
{
public static void main(String args[])
{
A a = new C();
B b = (B)a;
}
}
Here the compiler has no added knowledge without a very complex analysis of what what 'a' points to rather than just knowing that it is an 'A'.