0
interface I{
}
class A implements I{
}

class B extends A {
}

class C extends B{

    public static void main(String args[])
    {
        A a = new A();
        B b = new B();

        b = (B)(I)a; //Line 1
    }
}

I know this is not an actual code :)

I just need to know how the casting gets done at Line 1.

I know the reference variable 'a' gets cast to Class B/Interface I.

But I am not sure of the sequence in which the casting takes place..can someone tell me which cast gets executed first.

PS : I searched for similar posts but most of them were from C++.If a similar post is already there wrt to Java do point it..tx

1
  • You can't cast a cast to a cast: a -> I -> B. Commented Aug 25, 2013 at 15:42

2 Answers 2

3

a gets cast to type I first, and then to type B, as casting is right-associative.

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

Comments

0

Why would you cast it in the first place? This is multiple level inheritance but what happens here is all them methods in class I get inherited by class A, as class B inherits class A the methods in class A get passed onto class B. This means that all the methods class A inherits will also be in class B

That means class B is also a type of class I and therefore i believe there is no need to cast at all

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.