With A SpiRIT
With A SpiRIT

Reputation: 538

Accessing indirect super class variable that has been hidden in a third extended class

Suppose i have a code as below :

    class A {
    int a = 1; 
    }

    class B extends A {
    int a = 2; 
    }

    class C extends B {
    int a = 3;

    void print_it() {
    int a = 4;  // Local variable "a" to the " print_it " method

    System.out.println(a);       //Should be 4

    System.out.println(this.a);  //Should be 3

    System.out.println(super.a); //Should be 2

    System.out.println("HOW DO I PRINT \" a \" OF THE \" CLASS A      \" ");      //I need to print 1  
    }

    public static void main(String[] argue) {
    C obj = new C();               
    obj.print_it();
    } 
    }

How can i access "a" of the "class A" indirectly inherited to "class C".I know i can create an object of the " class A ", i also know i can create a method in "class B" to return "super.a" ( "a" variable of the "class A"), of course if it were static i could have accessed it like "A.a".

If there is any other method to access it directly kindly enlighten me.

(thanks in advance).

Upvotes: 1

Views: 260

Answers (1)

wero
wero

Reputation: 32980

Cast to A and then access the variable:

((A)this).a

Upvotes: 2

Related Questions