• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting rules for interface

 
Ashwin Sharma
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
First of all let me explain the problem->
compiler forces you to cast when type cannot be determined at complie time(i.e automatic conversion won't be done by it).... By this rule it automatically converts the type to that of base type even if the type is far down the hiererchy.... It will give comile time error for the following code, even if casted, as two classes are not related....
class A{}
class B{}
class C{
void method(){
A a = new A();
B b = (B)a;
}
}

But the problem is, same thing you try with interfaces it will compile....
interface A{}
class C{
void method()
{
C c = new C();
A a = (A)c;
c = (C)a;
}
}

Here though the class C doed not implements the interface it will complie, though run time error will be thrown;
My querry is if the compiler have sufficient information at compile time to know whether the perticular class immplements the interface or not and then throw the error then and there, why does it leaves it to be caught at run time instead.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ashwin,

this was you first post, so welcome to the Java Ranch!



You could make an instanceof test.

Generally, a (non-final) class can be cast to any interface, even if it does not implement it. This is because a subclass could implement the interface. So this cast must be possible.
If the non-implementing class was final, the casting would not compile.

Yours,
Bu.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With other words, for the line

A a = (A)c;

the compiler *does not* know that c references an instance of C - it could also reference an instance of a subclass of C, for which the cast might be valid.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic