静态常量在匿名类中有什么作用?

huangapple go评论102阅读模式
英文:

How is a static constant useful in an anonymous class?

问题

匿名类的文档说明:

匿名类在其成员方面与局部类具有相同的限制:

  • 无法在匿名类中声明静态初始化器或成员接口。
  • 匿名类可以拥有静态成员,只要它们是常量变量。

我不明白在实践中如何使用匿名类中的静态常量。静态方法无法被覆盖,而且我们无法从外部访问匿名类的成员,因此我们不需要使用静态常量。

我是否漏掉了什么,还是说这在任何情况下都不实用,但仍然被允许?

英文:

The documentation for the anonymous classes states:

> 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.

I don't understand how would a static constant in an anonymous class be useful in practice. Static methods can't be overridden and we can't access the anonymous class's members from outside, therefore we don't need to use static constants.

Am I missing something or is it something that's not practical in any way, but it's permitted anyways?

答案1

得分: 2

你漏掉了:

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

  2. 给常量命名可以使它在匿名类代码的多个位置中使用,使得稍后更容易在不漏掉任何地方的情况下进行更改。

这实际上与在任何其他类中使用“private”常量没有什么不同。

英文:

You're missing:

  1. Naming constants provide clarity to the programmers that needs to maintain the code.

  2. Naming a constant allows it to be used in multiple places in the anonymous class code, making it easier to change later without missing a spot.

This is really no different than using private constants in any other class.

huangapple
  • 本文由 发表于 2020年9月2日 21:39:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63706803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定