0

How can i access the x = 15 value from m2() ? I am accessing following values as given in comment of the program.

  class A  {
        int x = 10;
        void m1(){
        int x = 15;     //How can we access x =15 ?

  class B{
        int x =20;
           void m2(){
            int x = 25;
            System.out.println(x);          //for x = 25
            System.out.println(this.x);     //for x = 20
            System.out.println(A.this.x);   //for x = 10
            System.out.println();           
            }
        }
    }
}
Sagar
  • 5,273
  • 4
  • 37
  • 50
  • 1
    [What is variable shadowing used for in a Java class](https://stackoverflow.com/questions/1092099/what-is-variable-shadowing-used-for-in-a-java-class) may answer your question. Long story short: you can't. – Obicere Feb 15 '18 at 06:53
  • I think there's a misplaced closing brace somewhere – Mad Physicist Feb 15 '18 at 06:57

2 Answers2

0

B is an inner class inside A. So, when you want to reference the outer class, use A.this, you want to use m1 from the outer class, so use A.this.m1()

user9335240
  • 1,739
  • 1
  • 7
  • 14
0

Actually, you can't get access to x defined in m1(). To fix it, you could change the variable name: void m1() { int a = 15; ...}, or much better to use different names for all variables, because readability will be much higher (and at the first look, developer will not be hesitated what variable is used in every place):

public class A {
    private int a = 10;

    public void m1() {
        int m = 15;

        class B {
            private int b = 20;

            void m2() {
                int x = 25;
                System.out.println(x);  // x = 25
                System.out.println(a);  // a = 10
                System.out.println(b);  // b = 20
                System.out.println(m);  // m = 15
            }
        }
    }
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35