How can I access variables outside of the class, but inside the scope of the parent class?

I have an example exam that asks if I can access the variable x containing the value 1? The solution is that I can, but I am wondering how exactly?

class A {
    int x = 1; //this is what I need access to.
    class B {
        int x = 2;
        void func(int x) {...}
    }
}

      

+3


source to share


3 answers


class A {
    int x = 1;

    class B {
        int x = 2;

        void func(int x) {
            System.out.println(A.this.x);
        }
    }
}

      

Usage example:



public class Main {
    public static void main(String[] args) {        
        A a = new A();
        A.B b = a.new B();

        b.func(0); // Out is 1
    }
}

      

+2


source


To access the parent instance you use this keyword as in ParentClassName.this



Child class should not be static

+1


source


Yes you can access variable x with value 1.

Here A is your outer class and B is your non-static inner class.

To access variable x of outer class A, you can do something like this

class B {
    int x = 2;
    void func(int x) {
      System.out.print(A.this.x +"  and  "+x);
    }
}

      

+1


source







All Articles