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

时间:2015-04-28 06:37:53

标签: java encapsulation inner-classes nested-class

我做了一个外课和内课。这两个类都有变量int x。如何在内部类中访问外部类的xthis.x无效。

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

4 个答案:

答案 0 :(得分:5)

你可以试试这个:

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

答案 1 :(得分:1)

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

/* 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

答案 2 :(得分:0)

使用OuterClass.this.x; OuterClass.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 = 1引用x内部类的公共字段FirstLevel,{ {1}}指的是ShadowTest.this.x = 0外层的公共字段x

答案 3 :(得分:-1)

其他方式是将外部成员设为受保护

public class OuterClass {

 protected int x=10,y=20;

private class InnerClass {

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

  }

 }