简体   繁体   English

如何访问本地内部类中的外部类方法局部变量?

[英]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. 如何在InnerClass print()方法内调用MyClass test()方法局部变量x What i can write in place of ? 我可以代替什么写 in last System.out.println() method in order to get the value of test() x . 在最后的System.out.println()方法中,以获取test() x的值。

Unfortunately in Java you can't. 不幸的是,在Java您做不到。

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. 访问MyClass::testx的唯一方法是将内部类和内部类方法中的两个变量都重命名为其他变量。

There is no need though to rename the outer class field x as InnerClass::print would consider the variable in the most-inner scope. 无需将外部class字段x重命名为InnerClass::print会在最内部范围内考虑变量。

Although this snippet is for demonstration purposes, better practice would have you have different and more significant names for each variable. 尽管此代码段是出于演示目的,但更好的做法是让您为每个变量使用不同且更重要的名称。

That works fine for me: 这对我来说很好:

public class Outerclass {

    public static void main(String args[]) {
        Outerclass outer = new Outerclass();
        outer.outerMethod();
    }

    // method of the outer class 
    void outerMethod() {
        int num = 23;

        // method-local inner class
        class MethodInnerClass {
            public void print() {
                System.out.println("This is method inner class "+num);
            }
        }
        // Accessing the inner class
        MethodInnerClass inner = new MethodInnerClass();
        inner.print();
    }
}

打印外部类变量使用

 MyClass.this.x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM