Dániel Kriston Dániel Kriston - 3 months ago 14
Java Question

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

I have an exam example which ask whether or not can I access the x variable containing the value 1? The solution is that I can, but I'm interested how exactly?

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

Answer Source
class A {
    int x = 1;

    class B {
        int x = 2;

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

Using 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
    }
}