File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes casting rules for interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "casting rules for interface " Watch "casting rules for interface " New topic

casting rules for interface

Ashwin Sharma

Joined: Nov 03, 2006
Posts: 28
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

Joined: Aug 25, 2006
Posts: 1274
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.


all events occur in real time
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
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.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: casting rules for interface
It's not a secret anymore!