-4

How can I access variable int a=89; of Outer class inside my Inner class? Check my code. Help me to solve this.

public class TestOuter {
    private String name = "Makky";
    int a = 1;

    public void dis() {
        System.out.println("dis");
        int a = 89;
        class TestInner {
            int a = 6;

            void dis() {
                int a = 12;
                System.out.println("local inner class=" + a);
                System.out.println("local inner class=" + this.a);
            }
        }
        TestLocalInner ob = new TestLocalInner();
        ob.dis();
    }

    private class TestInner {
        int a = 2;

        public void access() {
            int a = 3;
            System.out.println("a=" + a);
            System.out.println("name=" + name);
            System.out.println("a=" + this.a);
            dis();
        }
    }

    public static void main(String[] args) {
        TestOuter.TestInner inner = new TestOuter().new TestInner();
        inner.access();
        TestOuter outer = new TestOuter();
        System.out.println(outer.a);
    }
}

Here I want to access variable int a = 89 of dis() method in my Inner Class without print value of a=89 inside that dis method like System.out.println(a);

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 1
    Have you tried your inner class variables to something other than `a`? – Joe C Aug 05 '17 at 10:28
  • No m just want to use same name a – Mayank Tyagi Aug 05 '17 at 10:31
  • Check [this](https://stackoverflow.com/questions/33718123/how-a-class-inside-a-method-access-a-local-variable-of-that-method) out. – BakaWaii Aug 05 '17 at 10:34
  • Please help me to solve my CODING PROBLEMS not my editing skills I was clearly mention that "I AM A BEGINNER HERE" – Mayank Tyagi Aug 05 '17 at 10:46
  • You can't. Local variables ware not meant to be accessed/manipulated from local classes (unless they ware final to prevent their manipulation). If you are interested in knowing its value you can add another field in your class to store copy of that value. Anyway simplest solution would not be using same names to prevent shadowing. – Pshemo Aug 05 '17 at 10:54
  • 1
    I would classify poorly-named variables as a coding problem, because you will very easily lose track of what each `a` means and which `a` is which. – Joe C Aug 05 '17 at 13:19

1 Answers1

0

TestInner member: this.a
TestInner.dis local variable: a
TestOuter member: TestOuter.a

clabe45
  • 2,354
  • 16
  • 27