静态常量在匿名 class 中有何用处?

How is a static constant useful in an anonymous class?

匿名 classes 的 documentation 指出:

Anonymous classes also have the same restrictions as local classes with respect to their members:

  • You cannot declare static initializers or member interfaces in an anonymous class.
  • An anonymous class can have static members provided that they are constant variables.

我不明白匿名 class 中的 static 常量在实践中有何用处。静态方法不能被覆盖,我们不能从外部访问匿名class的成员,因此我们不需要使用静态常量。

我是不是遗漏了什么,或者它是不是在任何方面都不实用,但无论如何都是允许的?

你错过了:

  1. 命名常量为需要维护代码的程序员提供清晰度。

  2. 命名常量允许它在匿名代码中的多个地方使用class,使得以后更容易更改而不会遗漏一个地方。

这与在任何其他 class 中使用 private 常量没有什么不同。