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.

Advertisements