是的,Enum在Java 中實作了一個接口,當我們需要實作一些與給定物件或類別的可區分屬性緊密耦合的業務邏輯時,它會很有用。 枚舉是Java 1.5版本中新增的一種特殊資料類型。 枚舉是常數,預設情況下它們是靜態的 strong>和final,因此枚舉類型欄位的名稱採用大寫字母。
interface EnumInterface { int calculate(int first, int second); } enum EnumClassOperator implements <strong>EnumInterface </strong>{ // <strong>An Enum implements an interface</strong> ADD { @Override public int calculate(int first, int second) { return first + second; } }, SUBTRACT { @Override public int calculate(int first, int second) { return first - second; } }; } class Operation { private int first, second; private EnumClassOperator operator; public Operation(int first, int second, EnumClassOperator operator) { this.first = first; this.second = second; this.operator = operator; } public int calculate() { return operator.calculate(first, second); } } <strong>// Main Class</strong> public class EnumTest { public static void main (String [] args) { Operation add = new Operation(20, 10, <strong>EnumClassOperator.ADD</strong>); Operation subtract = new Operation(20, 10, <strong>EnumClassOperator.SUBTRACT</strong>); System.out.println("Addition: " + add.calculate()); System.out.println("Subtraction: " + subtract.calculate()); } }
<strong>Addition: 30 Subtraction: 10</strong>
以上是在Java中,枚舉類型可以實作介面嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!