0

I am learning for a JAVA Programmer I certificate and among questions there is one I can't understand:

//Given:

interface I{}
class A implements I{}
class B extends A {}
class C extends B{}

//and

A a = new A();
B b = new B();

Identify options that will compile and run without error.

A. a = (B)(I)b;
B. b = (B)(I)a;
C. a = (I)b;
D. I i = (C)a;

Now I know that the answer is A) but I don't get it, if the class B is a child of class A, then 'a' can be equal to 'b' without casting, why is the answer B) wrong? What does even casting (B)(I) means?

1
  • look to it like this all B are A but not all A are B. In this example only B extends A but there might be a new class Z extends A which will be an A but will not be a B Commented Dec 4, 2018 at 20:29

2 Answers 2

2

B extends A. So you can cast instances of B to A but not the other way around. The code will compile, but will throw a ClassCastException at runtime.

Trying to cast to a descendant class is called downcasting. The cast to 'I' in this case is what would allow that code to compile, but result in the ClassCastException being thrown.

Sign up to request clarification or add additional context in comments.

Comments

0
  1. Parent reference can be used to hold child objects. Thus below all are correct.

    A a = new A();
    B b = new B();
    I i = new A();
    a = new B();
    b = new C();
    
  2. Below has attempted to cast an object to a subclass of which it is not an instance.Thus below will throw the CCE.

    b = (B)(I)a;
    c = (C)(I)a;
    

    You may check the same as System.out.println(a instanceof C);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.