gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:06 25 4
gpt4 key购买 nike

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

/* 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com