我认为我们无法实例化 Enum。那么我们是否需要为枚举提供 toString()、equals() 和 hashCode() 方法?这个说法属实吗?
也作为后续问题 下面的枚举类中的“this”关键字指的是什么?
public enum DocuType {
text, print, html, pdf; //Why aren't these in caps?
public boolean isPrint() {return this == print; } //What does this refers to?
public boolean isText() {return this == text; }
public boolean isTextOrPrint() { return isText() || isPrint(); }
}
如何调用此枚举的任何 boolean 方法,因为它们不是静态的? 另外,当我打电话时,关键字“this”指的是什么?
最佳答案
I don't think we can instantiate an Enum.
枚举是一种类型,因为我们有类类型。我们可以创建类的实例(即创建变量),类似地,我们可以创建 Enum 变量,但这只是在其定义期间,最终使它们成为常量。
So do we need to have toString(), equals() and hashCode() method for an enum?
equals() 和 hashcode() 用于比较两个实例。对于类实例,实例是动态创建的。因此,这意味着我们事先不了解实例,因此我们需要比较它们以了解它们是否相等。然而,对于枚举,我们在定义枚举时就知道实例。因此,我们事先知道它们是否相等。如果枚举实例意味着相等,为什么我们需要两个单独的相等的枚举实例。因此,对于枚举,我们通常不会重写这些方法。
What does "this" keyword refers to in the following enum class?
&
How do I call any of the boolean methods of this enum as they are not static?
&
Also when I call, what does the keyword "this" refers to ?
this 表示当前正在访问的实例。在您的示例中,您有 DocuType 实例,如文本、pdf、打印、html。当您在任何实例上调用方法时,例如:DocuType.text.isPrint(),isPrint 方法中的 this 关键字将指向 text嗯>。因此,例如 pdf,除了 isPdf() 之外,所有方法都将返回 false。
关于java - Java 中的枚举中是否有必要使用 toString() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788895/