简体   繁体   English

如何从Java中的嵌套类访问父类成员?

[英]How to access parent class member from nested class in Java?

Simple question for Java programmer - I am not sure if it possible directly - please present workarounds. Java程序员的简单问题 - 我不确定是否可以直接 - 请提供解决方法。

I want to access parent variable to initialize nested class member but not know the Java syntax to do it (if it possible). 我想访问父变量来初始化嵌套的类成员,但不知道要执行它的Java语法(如果可能)。 How to set Child id with parent id. 如何使用父ID设置子ID。

public class Parent {
    final String id = "parent";

    class Child {
        // it is invalid since scope hide parent id?
        final String id = id;
    }
}

The best solution with I found is very ugly see here: 我发现的最佳解决方案非常难看,请看:

public class Parent {
    final String id = "parent";

    // ugly clone
    String shadow = id;

    class Child {
        final String id = shadow;
    }
}

Please help with syntax - I do not know how to express it. 请帮助语法 - 我不知道如何表达它。

您可以使用其完全限定名称来访问它:

final String id = Parent.this.id;

How about if you change one of the String id. 如果你改变其中一个String id怎么样。

public class Parent {
  final String id = "parent";

  class Child {
    // it is invalid since scope hide parent id?
    // Instead of using id use ID
    final String ID = id;
  }
}

This way you would not have string id = id, which does not make sense. 这样你就不会有字符串id = id,这没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM