Java类中是否可以定义一个枚举?
Java 中的枚举表示一组命名常量,你可以使用以下语法创建一个枚举
enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
是的,我们可以在类中定义枚举。可以使用values()方法检索枚举中的值。
示例
public class EnumerationExample { enum Enum { Mango, Banana, Orange, Grapes, Thursday, Apple } public static void main(String args[]) { Enum constants[] = Enum.values(); System.out.println("Value of constants: "); for(Enum d: constants) { System.out.println(d); } } }
输出
Value of constants: Mango Banana Orange Grapes Thursday Apple
示例
enum Vehicles { //Declaring the constants of the enum ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER; int i; //Instance variable Vehicles() { //constructor } public void enumMethod() { //method System.out.println("Current value: "+Vehicles.this); } } public class Sam{ public static void main(String args[]) { Vehicles vehicles[] = Vehicles.values(); for(Vehicles veh: vehicles) { System.out.println(veh); } vehicles[3].enumMethod(); } }
输出
ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Current value: VESPA
广告