3

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) {...}
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

3 Answers3

3
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
    }
}
Andrey
  • 191
  • 4
  • 13
1

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

The child class must not be static

kosgeinsky
  • 508
  • 3
  • 21
1

Yes you can access variable x with value 1.

Here A is your outer class and B is Non-Static inner class.

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

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