Page 1 of 1

[HD Pg 308, Sec. 11.3.1 - casting-a-reference-to-an-interface]

Posted: Fri Mar 22, 2019 1:10 pm
by OCAJO1

Code: Select all

class Fruit{ }
class Apple extends Fruit{ }
class Mango extends Fruit{ }
interface Poisonous{ }

class TestClass{

    public static void main(String[] args){
        Fruit f = new Mango(); //ok, because Mango is-a Fruit
        Poisonous p = (Poisonous) f; //compiles fine but throws a ClassCastException at run time
    }
}

class StarFruit extends Fruit implements Poisonous{
        public static void main(String[] args){
            Fruit f = new StarFruit();
            Poisonous p = (Poisonous) f; //compiles and runs fine
        }
}
Unlike the comment by the line casting f as poisonous in the TestClass, I did not get any ClassCastException before or after the introduction of StarFruit class! Since class Fruit is not final, I did not expect a compiler error as stated in the comment, but does JVM accept this casting as well?

Re: [HD Pg 308, Sec. 11.3.1 - casting-a-reference-to-an-interface]

Posted: Fri Mar 22, 2019 4:30 pm
by admin
well, try it out :)

Re: [HD Pg 308, Sec. 11.3.1 - casting-a-reference-to-an-interface]

Posted: Fri Mar 22, 2019 5:06 pm
by OCAJO1
No wonder it didn't throw an exception, I was doing some stuff down the line with catch RuntimeException and no remedy. So as they say, it swallowed the ClassCast one :geek: