简体   繁体   English

枚举中的静态最终方法

[英]static final methods in enum

So I have looked around google and SO , I cannot find a example or explanation of : What is the purpose of static final methods in enum ? 所以我浏览了谷歌和SO,我找不到一个例子或解释: enumstatic final方法的目的是什么?

What I understand : 我的理解:

  1. Methods declare static can be accessed like function/procedural languages. 声明static方法可以像函数/过程语言一样被访问。
  2. final means you can't override it. final表示你无法覆盖它。 Can't change the reference. 无法更改参考。 As assylias pointed out in comments static can't be overridden either. 正如assylias在评论中指出的那样, static也不能被覆盖。
  3. enum s can't be subclassed, explained here . enum s不能被子类化, 这里解释。

So what's the point of static final methods in enum s if it will never be overridden since there won't be a subclass? 那么enumstatic final方法有什么意义,如果它永远不会被覆盖,因为它不会有子类?

By making a static method final, you prevent it from being hidden (only instance methods can be overriden) by a subclass. 通过使静态方法最终, 可以防止子类隐藏它 (只有实例方法可以覆盖)。

Since enum can't be subclassed, making a static method final is superfluous but not forbidden. 由于enum不能被子类化,因此制作静态方法final是多余的,但不是禁止的。

Note: technically, each enum constant that has a class body implicitly defines an anonymous class that extends the enum . 注意:从技术上讲,每个具有类主体的枚举常量都隐式定义了一个扩展枚举的匿名类 But since inner classes may not declare static methods , the static final method could not be hidden in such a constant's class body. 但由于内部类可能不会声明静态方法 ,因此静态final方法不能隐藏在这样的常量类体中。

It's easy to see why static methods make sense, so I guess the question is about the final modifier. 很容易理解为什么static方法有意义,所以我想问题是关于final修饰符。

final serves no purpose here, except maybe make the code a bit easier to read, but not by much. final在这里没有任何意义,除了可能使代码更容易阅读,但不是很多。

It's similar to the way interface methods are often written as public void foo(); 它类似于interface方法通常被编写为public void foo(); , even though interface members are always public anyway. 即使接口成员总是公开的。

在Java中,Enum类型用于表示固定的常量集,并使其成为静态final,仅帮助其初始化一次,单个副本在所有实例之间共享,使用类名访问变量,最后更像是只读

When you declare instances of an enum you can override the enum's methods, essentially enum instances are implemented as (or thought of) as subclasses. 当您声明枚举的实例时,您可以覆盖枚举的方法,实际上枚举实例被实现为(或想到)子类。 static methods can't be overridden in any case but the implication in the OP and other answers that final is superfluous for an enum is false. static方法不能在任何情况下被覆盖,但在OP和其他答案的暗示final是多余的一个enum是假的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM