英文:
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
你漏掉了:
-
命名常量可以为需要维护代码的程序员提供清晰的信息。
-
给常量命名可以使它在匿名类代码的多个位置中使用,使得稍后更容易在不漏掉任何地方的情况下进行更改。
这实际上与在任何其他类中使用“private”常量没有什么不同。
英文:
You're missing:
-
Naming constants provide clarity to the programmers that needs to maintain the code.
-
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论