【Java教学系列】-- 枚举类型

枚举的作用是在编程语言中表示一组命名常量。例如,一副扑克牌中的4种花色可以表示为4个名为梅花、菱形、红桃和黑桃的枚举器,它们属于一个名为花色的枚举类型。

Java中,枚举使用enum数据类型来表示,里面可以添加变量,方法和构造器。

枚举类型声明

枚举类型的声明可以在类的外面,也可以在类的里面,但是不能声明在方法内部。

// enum declared outside a class
enum Color { 
    RED, GREEN, BLUE; 
} 

public class Test { 
    // Driver method 
    public static void main(String[] args) { 
        Color c1 = Color.RED; 
        System.out.println(c1); 
    } 
}
// enum declared inside a class
public class Test { 
    enum Color { 
        RED, GREEN, BLUE; 
    } 
  
    // Driver method 
    public static void main(String[] args) { 
        Color c1 = Color.RED; 
        System.out.println(c1); 
    } 
}

常用方法

valueOf()

返回指定字符串值的枚举常量;

values()

返回枚举中存在的所有值;

ordinal()

返回枚举中常量的索引;

// Java program to demonstrate working of values(), 
// ordinal() and valueOf()
enum Color { 
    RED, GREEN, BLUE; 
}
public class Test { 
    public static void main(String[] args) { 
        // Calling values() 
        Color arr[] = Color.values(); 
  
        // enum with loop 
        for (Color col : arr) { 
            // Calling ordinal() to find index of color. 
            System.out.println(col + " at index "
                             + col.ordinal()); 
        } 
  
        // Using valueOf(). Returns an object of 
        // Color with given constant. 
        // Uncommenting second line causes exception 
        // IllegalArgumentException 
        System.out.println(Color.valueOf("RED")); 
        // System.out.println(Color.valueOf("WHITE")); 
    } 
}

/**
* Output:
* RED at index 0
* GREEN at index 1
* BLUE at index 2
* RED
*/

构造函数和方法

  • 枚举可以包含构造函数,它在枚举类加载时为每个枚举常量单独执行
  • 不能显式创建枚举对象,因此不能直接调用枚举构造函数
  • 枚举只能包含具体方法,即不包含任何抽象方法
enum Color { 
    RED, GREEN, BLUE;   
    // 构造函数应用于每一个常量
    private Color() { 
        System.out.println("Constructor called for : " + 
        this.toString()); 
    } 
  
    // 只能是具体的方法,不能用 abstract 修饰 
    public void colorInfo() { 
        System.out.println("Universal Color"); 
    } 
} 
  
public class Test {     
    // Driver method 
    public static void main(String[] args) { 
        // 不能显示创建枚举对象
        Color c1 = Color.RED; 
        System.out.println(c1); 
        c1.colorInfo(); 
    } 
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值