java - 访问内部类中字段的推荐/正确方法是什么?

标签 java inner-classes

假设我们有这个类和它的内部类:

/* Outer.java */
public class Outer {
    private static class Inner {
        private final Object foo;

        public Inner(Object foo) {
            this.foo = foo;
        }

        public Object getFoo() {
            return foo;
        }
    }

    Inner inner = parse(/* someMistery */);

    // Question: to access foo, which is recommended?
    Object bar = inner.getFoo();
    Object baz = inner.foo;
}

令我惊讶的是 inner.foo 能正常工作。

因为 foo私有(private)的,所以它只能通过getFoo()访问,对吧?

最佳答案

Since foo is private, it can be accessed only through getFoo(), right?

在这种情况下,Outer 也可以访问它,因为 InnerOuter 的成员。

6.6.1说:

[If] the member or constructor is declared private, [then] access is permitted if and only if it occurs within the body of the top level class that encloses the declaration of the member or constructor.

请注意,它被指定为可在包含声明的顶级类的主体内访问。

这意味着,例如:

class Outer {
    static class Foo {
        private Foo() {}
        private int i;
    }
    static class Bar {{
        // Bar has access to Foo's
        // private members too
        new Foo().i = 2;
    }}
}

是否使用 setter/getter 真的是个人喜好问题。这里的重要认识是外部类可以访问其嵌套类的私有(private)成员。

作为推荐,我个人会说:

  • 如果嵌套类是 private(只有外部类可以访问它),我什至不会费心给它一个 getter,除非 getter 进行计算。它是任意的,其他人可以选择不使用它。如果风格混杂,代码就有模糊性。 (inner.fooinner.getFoo() 真的做同样的事情吗?我们不得不浪费时间检查 Inner 类来找到出。)
  • 但是如果您喜欢这种风格,您无论如何都可以使用 getter。
  • 如果嵌套类不是private,则使用 getter 以使样式统一。

如果你真的想隐藏 private 成员,甚至对外部类隐藏,你可以使用带有本地类或匿名类的工厂:

interface Nested {
    Object getFoo();
}

static Nested newNested(Object foo) {
    // NestedImpl has method scope,
    // so the outer class can't refer to it by name
    // e.g. even to cast to it
    class NestedImpl implements Nested {
        Object foo;

        NestedImpl(Object foo) {
            this.foo = foo;
        }

        @Override
        public Object getFoo() {
            return foo;
        }
    }

    return new NestedImpl(foo);
}

请注意,您的static class Inner {} 在技术上是static 嵌套类,而不是内部类class Inner {}(没有 static)将是一个内部类。

这是 specifically defined是这样的:

The static keyword may modify the declaration of a member type C within the body of a non-inner class or interface T. Its effect is to declare that C is not an inner class.

关于java - 访问内部类中字段的推荐/正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30200280/

相关文章:

java - 从数组执行的操作

java - 如何在main方法中访问匿名内部类?

java - 需要 ContentProvider 来访问 SharedPreferences

Java 泛型 'Incompatible Type' 编译时错误

JFrame 中的 Java 多线程

Javascript:eval 中的 replaceAll 不起作用

java - 对使用 UDP 套接字的代码进行单元测试的推荐方法是什么?

java - 授权 Flash Client 到 Java Server 连接

java - 匿名内部类 - getClass()

java - 私有(private)内部类的构造函数也是私有(private)的吗?