aspose file tools*
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "casting rules for interface " Watch "casting rules for interface " New topic
Author

casting rules for interface

Ashwin Sharma
Greenhorn

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.

Yours,
Bu.


all events occur in real time
Ilja Preuss
author
Sheriff

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
 
Don't get me started about those stupid light bulbs.
 
subject: casting rules for interface