Zhu Li
Zhu Li

Reputation: 595

How to reference a shadowed variable in the superclass of a superclass?

This is a simple example of inheritance where there is a shadowed variable x.

class A{
    int x=1;
}
class B extends A{
    int x=2;
}
class C extends B{
    int x=3;
    int y;
}

How can I reference the shadowed variable x of class A in class C?(I want something like y=super.super.x; that works well.)

Upvotes: 1

Views: 551

Answers (3)

TimoStaudinger
TimoStaudinger

Reputation: 42460

To my knowledge, there is no way to achieve this the way you imagine. Your best bet would be to implement an access method in your class B:

class B extends A{
    int x=2;

    protected int getXFromA() {
        return super.x;
    }
}

This way you would be able to access the value of x as defined in class A from class C.

I would be very interested in your use case, though. Considering object oriented design, what reason could there be to directly access A's members from C? If this is the case, from an OOP perspective, C could not really be considered a proper subclass of B anymore.

Upvotes: 2

Michael Macha
Michael Macha

Reputation: 1781

Not as hard as you might think. (While I strongly encourage avoiding this situation,) if you have a class C that inherits from class B, which in turn inherits from class A, all of which implement a public field x, then using super is usually the wrong way to go about it.

Instead, given class C, try this:

((A)this).x;   //don't forget the parentheses!

that will give you the value of x for A. Also,

super.x == ((B)this).x;

which is generally why, for single steps, we usually just use super.

Hopefully that helps.

Upvotes: 3

jaco0646
jaco0646

Reputation: 17066

class A {
    int x = 1;
}
class B extends A {
    int x = 2;
}
class C extends B {
    int x = 3;
    int y = ((A) this).x;
}

Note that shadowing is generally discouraged due to the confusion it can cause.

Upvotes: 1

Related Questions