如何访问同名的外部 class 变量?

How to access outer class variable of same name?

我做了一个外层和一个内层class。这两个 classes 都有变量 int x。如何在内部 class 中访问外部 class 的 xthis.x 不工作。

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

你可以试试这个:

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

其他方法是将外部 class 成员设置为 protected

public class OuterClass {

 protected int x=10,y=20;

private class InnerClass {

    private void printSum(int x1,int y1) {
        x=x1;
        y=y1;
    }

  }

 }

使用OuterClass.this.xOuterClass.this 引用父对象(从中生成 InnerClass 对象)。

考虑以下在官方 Oracle 教程中发布的遮蔽示例:

public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}

与输出

x = 23
this.x = 1
ShadowTest.this.x = 0

x = 23指方法void methodInFirstLevel()的局部变量,this.x = 1FirstLevel的public字段x inner-class,而ShadowTest.this.x = 0指的是ShadowTest outer-class.

的public字段x

如果你想这样做,你需要先实例化外部 class,然后像这样实例化内部:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    int x,y,sum;

    public static void main (String[] args) throws java.lang.Exception
    {
        //Create outer object
        Ideone ideOne = new Ideone();

        //instantiate inner object, and call method
        Ideone.InnerClass ic = ideOne.new InnerClass();
        ic.printSum(5,4);
    }


    private class InnerClass {
        private void printSum(int x,int y) {
            //reference the outer object instance
            Ideone.this.x=x;
            Ideone.this.y=y;
            Ideone.this.sum = x + y;
            System.out.println(Ideone.this.sum);
        }
    }
}

这里已经测试过:http://ideone.com/e.js/DRIzSg

Output: 9