Varun
Varun

Reputation: 3311

Multiple casting on inherited objects

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

Upvotes: 0

Views: 76

Answers (2)

Luka
Luka

Reputation: 76

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

Upvotes: 0

qaphla
qaphla

Reputation: 4733

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

Upvotes: 3

Related Questions