Java枚举 自定义枚举 通过enum关键字定义枚举 实现接口 枚举的方法

  1. 自定义枚举类
    public class TestEnum1 {
    	public static void main(String[] args) {
    		
    		Person man = Person.MAN;
    		System.out.println(man.toString());
    		Person woman = Person.WOMAN;
    		System.out.println(woman);
    	}
    }
    //自定义枚举类型
    class Person{
    	//1 属性私有化
    	private final String name;
    	private final int age;
    	//2 构造器私有 化
    	private Person(String name,int age) {
    		this.name = name;
    		this.age = age;
    	}
    	//3 创建对象 
    	public final static Person MAN = new Person("小明",20);
    	public final static Person WOMAN = new Person("小花",23);
    	@Override
    	public String toString() {
    		return "Person [name=" + name + ", age=" + age + "]";
    	}
    }
    

     

  2. 通过enum关键字定义枚举
    public class TestEnum2 {
    	public static void main(String[] args) {
    		Person1 man = Person1.MAN;
    		System.out.println(man.info());
    		Person1 woman = Person1.WOMAN;
    		System.out.println(woman.info());
    	}
    }
    enum Person1{
    	MAN("小明",20),
    	WOMAN("小花",24);
    	//1 属性私有化
    	private final String name;
    	private final int age;
    	//2 构造器私有 化
    	
    	private Person1(String name,int age) {
    		this.name = name;
    		this.age = age;
    	}
    	public String info() {
    		return "Person1 [name=" + name + ", age=" + age + "]";
    	}
    }
    

    注意:创建对象必须放在最枚举类的最前面

  3. 如何实现接口
    interface Interface1{
    	void show();
    }
    enum Person1 implements Interface1{
    	MAN("小明",20){
    		public void show() {
    			System.out.println("男人");
    		}
    	},
    	WOMAN("小花",24){
    		public void show() {
    			System.out.println("女人");
    		}
    	};
    	//1 属性私有化
    	private final String name;
    	private final int age;
    	//2 构造器私有 化
    	
    	private Person1(String name,int age) {
    		this.name = name;
    		this.age = age;
    	}
    	public String info() {
    		return "Person1 [name=" + name + ", age=" + age + "]";
    	}
    	@Override
    	public void show() {
    		System.out.println("这是人类");
    		
    	}
    }
    

     

  4. 枚举中方法使用
    //两个常用的方法 values()  valueOf(String)
    		//values()获取枚举类中的所有对象 
    		Person1[] ps = Person1.values();
    		for(Person1 p : ps) {
    			System.out.println(p.info());
    		}
    		System.out.println("=============");
    		//valueOf(对象字符串)获取其中一个
    		Person1 p1 = Person1.valueOf("MAN");
    		System.out.println(p1.info());
    		Person1 p2 = Person1.valueOf("WOMAN");
    		System.out.println(p2.info());
    

     

你可能感兴趣的:(Java笔记,Java)