如何从内部类访问outerclass字段?

gk7wooem  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(383)

我已经学习java和oop几个星期了。
昨天我学习了内课和外课。我想知道当它们的名称完全相同时,如何从内部类访问outerclass的字段。
如下所示,当它们有不同的名称时,可以从内部类访问outerclass的字段。

public class OuterClass { 
    public String OuterName;
    public OuterClass(String OuterName) {
        this.OuterName = OuterName;
    }
    public class InstanceInnerClass {
        public String InnerName;
        public InstanceInnerClass(String InnerName) {
            this.InnerName = InnerName;
        }
        // In this method, accessing field in outer and inner class is possible. 
        // when they have different name.
        public void printAllName() {
            System.out.printf("OuterName: %s, InnerName: %s\n", OuterName, InnerName);
        }
    }
}

当他们有相同的名字,我不知道如何访问这两个名字。

public class OuterClass { 
    public String name; // field which has same name
    public OuterClass(String name) {
        this.name = name;
    }
    public class InstanceInnerClass {
        public String name; // field which has same name
        public InstanceInnerClass(String name) {
            this.name = name;
        }
        public void printAllName() {
            // What should be written in this code 
            // to print both name fields from OuterClass and InnerClass
            System.out.printf("OuterName: %s, InnerName: %s\n", name, name);
        }
    }
}
ffx8fchx

ffx8fchx1#

田野 OuterClass 可在中访问 InnerClass 通过 OuterClass.this :

public void printAllName() {
    // to print both name fields from OuterClass and InnerClass
    System.out.printf("OuterName: %s, InnerName: %s\n", OuterClass.this.name, this.name);
}

测试:

OuterClass outer = new OuterClass("myOuter");
OuterClass.InstanceInnerClass inner = outer.new InstanceInnerClass("myInner");

inner.printAllName();

印刷品:

OuterName: myOuter, InnerName: myInner
n3h0vuf2

n3h0vuf22#

简单地做 OuterClass.this 以及 OuterClass 例如,您想要访问的 OuterClass.this.OuterName . 在您的代码中,如下所示:

public class OuterClass {
    public String name; // field which has same name
    public OuterClass(String name) {
        this.name = name;
    }
    public class InstanceInnerClass {
        public String name; // field which has same name
        public InstanceInnerClass(String name) {
            this.name = name;
        }
        public void printAllName() {
            // What should be written in this code
            // to print both name fields from OuterClass and InnerClass
            System.out.printf("OuterName: %s, InnerName: %s\n", name, OuterClass.this.name);
        }
    }
}

当您有两个同名字段,一个在内部类,另一个在外部类(即阴影),并且您试图从内部类访问该字段时,编译器假定您想从内部类访问该字段,而忽略外部类的另一个字段。否则,就无法选择使用哪个变量。
阴影
如果特定作用域(如内部类或方法定义)中的类型声明(如成员变量或参数名)与封闭作用域中的另一个声明具有相同的名称,则该声明将隐藏封闭作用域的声明。不能仅通过名称引用带阴影的声明。

相关问题