Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access outer class method local variable in local inner class?

public class MyClass {
    int x=9;
    public static void main(String args[]) {
       MyClass  myClass = new MyClass();
       myClass.test();
    }

    public void test(){
        int x=10;

        class InnerClass{
            int x = 11;

            void print(){
               int x = 12;
               System.out.println(x); 
               System.out.println(this.x); 
               System.out.println(MyClass.this.x); 
               System.out.println("MyClass => test() => x :" + "?");
            }
        }
        InnerClass innerClass = new InnerClass();
        innerClass.print();
    }
}

How to call MyClass test() method local variable x inside the InnerClass print() method. What i can write in place of ? in last System.out.println() method in order to get the value of test() x.

like image 985
Ankit Kumar Avatar asked Mar 13 '26 01:03

Ankit Kumar


1 Answers

Unfortunately in Java you can't.

The only way to access the x in MyClass::test would be to rename both variables in your inner class and in your inner class method into something else.

There is no need though to rename the outer class field x as InnerClass::print would consider the variable in the most-inner scope.

Although this snippet is for demonstration purposes, better practice would have you have different and more significant names for each variable.

like image 88
Marko Pacak Avatar answered Mar 15 '26 16:03

Marko Pacak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!