在Java中,枚舉類型是一種特殊的類,用于表示固定數量的常量值。定義枚舉類型的方法如下:
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public enum Color {
RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, BLACK
}
public abstract class Animal {
public abstract String getName();
public abstract int getAge();
}
public enum Dog extends Animal {
Buddy(2, "Buddy");
private int age;
private String name;
Dog(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public int getAge() {
return age;
}
}
public enum Box<T> {
INTEGER_BOX {
@Override
public T getValue() {
return (T) Integer.valueOf(42);
}
},
STRING_BOX {
@Override
public T getValue() {
return (T) "Hello, World!";
}
};
public abstract T getValue();
}
public interface Shape {
double getArea();
double getPerimeter();
}
public enum Circle implements Shape {
INSTANCE;
private final double radius = 5.0;
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
根據實際需求選擇合適的枚舉類型定義方式。