Java allows any class(this sentence is not totally true as you will come to know in a few lines below) to be type casted to any interface.
public interface FooInterface { public void roo(); } public class Moo { } Moo moo = new Moo(); FooInterface fooInterface = (FooInterface) moo;
The above will compile but will result in runtime error.
Q:Why this design in the language?
A:Runtime polymorphism. A super class can represent its subclass which may implement the interface the superclass is type casted to, as below.
public class SubMoo extends Moo implements FooInterface { public void roo() { } } Moo moo = new SubMoo(); FooInterface fooInterface = (FooInterface) moo;
The above will compile and also run.
If Java did not allow any class to be type casted to an interface, then the above would not have been possible.
Q:When does Java not allow a class to be type casted to an interface?
A:When the class is final.
public final class FinalBar { } FinalBar finalBar = new FinalBar(); FooInterface fooInterface = (FooInterface) finalBar;
The above will not compile. It does not make sense to allow the type casting as FinalBar can never be sub classed.
Hi Abhirama,
Just chanced upon this article of yours and liked it very much. I have been programming for quite some years now, extensively in some cases. Though I had come to learn this aspect through understanding gathered over years, the article brings the issue out very succinctly. Just wanted to sat ‘Well done!’ to you. For people who really want to understand programs, such nuggets of insights are eminently useful.
Thanks 🙂
According to me
Type Casting refers to changing an entity of one datatype into another
for me its useless artical
Thanks for dropping by Maulin. The entry was not written keeping your requirements in mind.