枚举的用法Enum

一、没学习枚举前我声明常量都是:public static  final  String str="SS"。认识了枚举,就方便多了。

例:

public enum Fruit {
	      //水果的尺寸  小杯   中杯   大杯
		small,
		medium,
		large;
}

用法:

public class TestEnum {

	public static void main(String[] args) {
		Fruit[] values = Fruit.values();
		for (Fruit fruit : values) {
			System.out.println(fruit);
		}
	}
}

打印结果:


二、Enum类型也可以用在switch语句中

例:

               Fruit ff = Fruit.small;
		switch (ff) {
			case small:
				System.out.println("我是"+ff);
				break;
			case large:
				System.out.println("我是"+ff);
				break;
			case medium:
				System.out.println("我是"+ff);
				break;
			default:
				break;
		}

打印结果为:

    

三、在枚举中添加自己的方法

public enum Fruit {
	//水果的尺寸  小杯   中杯   大杯
		small("小杯",1),
		medium("中杯",2),
		large("大杯",3);
	
	private String  name;
	private int index;
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(int index) {
		this.index = index;
	}

	private Fruit(String  name,int index) {//枚举中的构造方法不能为public,其不能为外部所调用
		this.name=name;
		this.index=index;
	}
}

例:

                String str="1";
		if(str.equals("1")) {
			System.out.println(Fruit.large.getIndex());
		}

打印结果:3

想要了解更多请搜索:https://blog.csdn.net/qq_27093465/article/details/52180865

猜你喜欢

转载自blog.csdn.net/shuoshuo_12345/article/details/80858235
今日推荐