Java-如果字段具有相同的名称,则如何访问外部类字段 [英] Java - How to access Outer class field if the fields have same name

查看:78
本文介绍了Java-如果字段具有相同的名称,则如何访问外部类字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码

class OuterClass{
    class InnerClass{
        int x;
        int y;
        void calculateX(){
            x = y+z;//I want to access the y field of the outer class
        }
        void printX(){
            print();
        }
    }
    int y;
    int z;
    InnerClass instance;
    OuterClass(int y,int z){
        this.y = y;
        this.z = z;
        instance = new InnerClass();
        instance.y = 10;
        instance.calculateX();
        instance.printX();
    }
    void print(){
        System.out.println("X:"+instance.x+"\nY:"+y+"\nZ:"+z+"\n");
    }
}

如果名称重叠,如何访问外部类的字段?

How to access field of the outer class if there is any overlap in name?

我尝试了以下操作:

x=super.y;
x=OuterClass.y;

并收到编译错误.

现实生活中是否会发生这种情况?

Will this kind of situation ever occur in real life programs?

推荐答案

最好的解决方案是为字段赋予有意义且可区分的名称.但这并不总是可能的...

The best solution is to give the fields meaningful and distinguishing names. But this is not always possible...

要获取字段或外部实例,您可以使用

To get a field or an outer instance you can use

OuterClass.this.y;

或者如果该字段是静态的

or if the field is static

OuterClass.y;

注意:y通常是this.y的缩写(取决于y的实际定义位置)

Note: y is often short for this.y (depending on where y actually is defined)

类似地,要调用所需的外部类的实例方法.

Similarly, to call an instance method of an outer class you need.

OuterClass.this.method();

OuterClass.method(); // static

注意:在Java 8中,您有可能基于实例的方法引用.例如

Note: in Java 8 you have method references which might be instance based. e.g.

 list.stream().filter(OuterClass.this::predicate);

这篇关于Java-如果字段具有相同的名称,则如何访问外部类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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