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

久未见 提交于 2020-01-11 12:05:14

问题


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).


回答1:


Cast to A and then access the variable:

((A)this).a


来源:https://stackoverflow.com/questions/34039824/accessing-indirect-super-class-variable-that-has-been-hidden-in-a-third-extended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!