contrl
contrl

Reputation: 109

How to specify which variable I want to use in object with multiple inheritance?

So I was getting deeper into some multiple inheritance Java stuff and hence my question:

class Base {
    static int x = 10;
}

interface Interface {
    int x = 20;
}

class MultipleInheritance extends Base implements Interface {   
    int z = 2 * Interface.x; // here I have both variables from interface and base class
    // I can use either "Interface" or "Base" to specify which 'x' variable I want to use
}

class TestClass {

    void aMethod(MultipleInheritance arg) {
        System.out.println("x = " + arg.x); // compiler error
        // how to specify which 'x' variable I want to use here?
    }

}

Upvotes: 1

Views: 75

Answers (2)

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

Unlike method reference the field reference is not polymorphic. They are resolved by the reference type during compilation.

If you have to use object reference you can cast the reference type yourself to decide which to use

System.out.println("x = " + ((Interface) arg).x); 
System.out.println("x = " + ((Base) arg).x);

Upvotes: 2

ernest_k
ernest_k

Reputation: 45309

You can cast:

System.out.println("x = " + ((Interface)arg).x);
System.out.println("x = " + ((Base)arg).x);

While you can do this, it's a bad practice to access static members through instances (you get a warning for that). So you should simply be referring the variable directly (the value is static, so it can't be different based on the instance through which it's accessed):

System.out.println("x = " + Interface.x);
System.out.println("x = " + Base.x);

Upvotes: 3

Related Questions