1

Trying to cast printable to interface Printable:

class Printable2{}
interface Printable {}
class BlackInk {}


class TwistInTaleCasting {
    public static void main(String args[]) {
        Printable printable = null;
        BlackInk blackInk = new BlackInk();
        printable = (Printable)blackInk;
    }
}

Got runtime exception:

Exception in thread "main" java.lang.ClassCastException: BlackInk cannot be cast to Printable
    at TwistInTaleCasting.main(TwistInTaleCasting.java:17)

Trying to cast printable to classPrintable2:

class Printable2{}
interface Printable {}
class BlackInk {}


class TwistInTaleCasting {
    public static void main(String args[]) {
        Printable2 printable = null;
        BlackInk blackInk = new BlackInk();
        printable = (Printable2)blackInk;
    }
}

Got error at compile time:

Error:(17, 33) java: incompatible types: BlackInk cannot be converted to Printable2

Why compiler does not checks interface cast and checks class cast?

vico
  • 17,051
  • 45
  • 159
  • 315

0 Answers0