Search code examples
javaencapsulationinner-classesnested-class

How to access outer class variable of same name?


I have made an Outer and an Inner class. Both these classes have variable int x. How to access x of Outer class in inner class. this.x is not working.

class OuterClass {
int x,y;
private class InnerClass {
    private void printSum(int x,int y) {
        this.x=x;
        this.y=y;
    }
  }
}

Solution

  • You can try this :

       private void printSum(int x,int y) {
           OuterClass.this.x=x;
           OuterClass.this.y=y;
        }