Java:如何通过使用“this”来访问外部类的实例变量? [英] Java: how to access outer class's instance variable by using "this"?

查看:420
本文介绍了Java:如何通过使用“this”来访问外部类的实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态内部类,其中我想使用外部类的实例变量。目前,我必须以Outerclass.this.instanceVariable的格式使用它,这看起来很奇怪,是否有更简单的方法来访问外部类的实例字段?

I have a static inner class, in which I want to use the outer class's instance variable. Currently, I have to use it in this format "Outerclass.this.instanceVariable", this looks so odd, is there any easier way to access the instance field of the outer class?

Public class Outer
{
  private int x;
  private int y;
 private static class Inner implements Comparator<Point>
{
  int xCoordinate = Outer.this.x;   // any easier way to access outer x ?
}
}


推荐答案

A static 嵌套类不能引用外部类实例,因为它的 static ,没有相关的外部类实例。如果你想让一个静态嵌套类引用一个外部类,传递一个实例作为构造函数的参数。

A static nested class cannot reference the outer class instance because it's static, there is no related outer class instance. If you want a static nested class to reference an outer class, pass an instance as a constructor argument.

public class Outer
{
    private int x;
    private int y;
    private static class Inner implements Comparator<Point>
    {    
        int xCoordinate;

        public Inner(Outer outer) {
            xCoordinate = outer.x;       
        }
    }
}

非 - static 嵌套)类和没有变量名冲突(即两个变量都叫同名),可以直接引用外部类变量

If you meant an inner (non-static nested) class and there is no variable name collision (ie. both variables called the same name), you can directly reference the outer class variable

public class Outer
{
    private int x;
    private int y;
    private class Inner 
    {    
        int xCoordinate = x;
    }
}

这篇关于Java:如何通过使用“this”来访问外部类的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆