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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

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

Post 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?

admin
Site Admin
Posts: 10043
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin »

well, try it out :)
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

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

Post 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:

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 37 guests