ไม่ได้ Java ไม่สามารถ extends Enum ได้ Enum ขยาย java.lang.Enum โดยอัตโนมัติ (Implicitly) จึงไม่สามารถ extends คลาสอื่นได้ (Java ไม่รองรับ Multiple Inheritance)
Enum ใน Java
- Data Type พิเศษ เพิ่มใน Java 1.5
- กำหนด Collection of Constants ค่าคงที่ที่รู้จักล่วงหน้า
- Constants เป็น static และ final โดยอัตโนมัติ ชื่อตัวใหญ่ (UPPER_CASE)
- Top-level Enum: ใช้ public หรือ default modifier เท่านั้น
- Nested Enum: ใช้ ทุก Access Modifier ได้
ตัวอย่าง Enum กับ Abstract Method
enum Country {
US {
public String getCurrency() { return "DOLLAR"; }
},
RUSSIA {
public String getCurrency() { return "RUBLE"; }
},
INDIA {
public String getCurrency() { return "RUPEE"; }
};
// Abstract method บังคับแต่ละ Enum Constant implement
public abstract String getCurrency();
}
public class ListCurrencyTest {
public static void main(String[] args) {
for (Country country : Country.values()) {
System.out.println(country.getCurrency() + " is the currency of " + country.name());
}
}
}
ผลลัพธ์
DOLLAR is the currency of US
RUBLE is the currency of RUSSIA
RUPEE is the currency of INDIA
สิ่งที่ Enum ทำได้ (แทน Extends)
- Implement Interfaces - Enum implements interface ได้หลายตัว
- มี Fields, Methods, Constructors - เป็น Class เต็มรูปแบบ
- Constant-specific Methods - แต่ละ Constant มี Implementation ต่างกัน (เหมือน Anonymous Class)
- ใช้ใน Switch Case - Type-safe Switch
ตัวอย่าง Implement Interface
interface CurrencyInfo {
String getSymbol();
double getExchangeRateToUSD();
}
enum Currency implements CurrencyInfo {
USD("$", 1.0),
EUR("€", 1.1),
JPY("¥", 0.0075);
private final String symbol;
private final double rate;
Currency(String symbol, double rate) {
this.symbol = symbol;
this.rate = rate;
}
public String getSymbol() { return symbol; }
public double getExchangeRateToUSD() { return rate; }
}
สรุป
Enum ไม่สามารถ Extends Class อื่น ได้ (เพราะ Extends java.lang.Enum แล้ว) แต่ Implements Interface ได้ และมีความสามารถเต็มรูปแบบเหมือน Class