在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;
}
}
根据实际需求选择合适的枚举类型定义方式。