1. 程式人生 > 其它 >Java-enum列舉

Java-enum列舉

1 列舉概述:

列舉:現實生活中有很多事物都是有限個的,比如一年只有四個季節,對應到java類中,一個季節類只能創建出4個物件,不能再多像這樣描述一個只有有限個物件,我們把這個類定義為列舉類。
  • 在JDK1.5之前呢,我們使用自定義列舉類
  • 在JDK1.5之後,java提供了enum關鍵字來定義列舉類

JDK1.5之前注意事項:

  • 1 成員變數私有化且用final關鍵字修飾,外界不能去修改也不能直接獲取
  • 2 構造方法私有化使用private關鍵字修飾,保證類的個數個有限;
  • 3 在列舉類中建立物件,因為外界無法建立物件,又想讓外界獲取,所以改成靜態的,可以直接通過類名訪問
  • 4 提供公共的get方法獲得屬性;
package com.bigdat.java.day19;
import javax.swing.*;
/*
        列舉:現實生活中有很多事物都是有限個的,比如一年只有四個季節,對應到java類中,一個季節類只能創建出4個物件,不能再多
        像這樣描述一個只有有限個物件,我們把這個類定義為列舉類。
        在JDK1.5之前呢,我們使用自定義列舉類
        在JDK1.5之後,java提供了enum關鍵字來定義列舉類
 */
class Season1{
    private final String SEASON_NAME;
    private final String SEASON_DESC;
    
    private Season1(String SEASON_NAME, String SEASON_DESC) {
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }
   public static final Season1 SPRING =  new Season1("Spring","春意黯然");
    public static final Season1 SUMMER =  new Season1("Summer","夏日炎炎");
    public static final Season1 AUTUMN =  new Season1("Autumn","碩果累累");
    public static final Season1 WINTER =  new Season1("Winter","寒風凌冽");

    public  String getSEASON_NAME() {
        return SEASON_NAME;
    }

    public String getSEASON_DESC() {
        return SEASON_DESC;
    }

    @Override
    public String toString() {
        return "Season1{" +
                "SEASON_NAME='" + SEASON_NAME + '\'' +
                ", SEASON_DESC='" + SEASON_DESC + '\'' +
                '}';
    }
}
public class EnumDemo1 {
    public static void main(String[] args) {
        //獲取春天並使用
        Season1 spring = Season1.SPRING;
        System.out.println(spring.getSEASON_NAME()+"-----"+ spring.getSEASON_DESC());
    }
}

在JDK1.5之後,java提供了enum關鍵字來定義列舉類

  • 注意事項:在列舉類中建立物件,因為外界無法建立物件,又想讓外界獲取,所以改成靜態的,可以直接通過類名訪問在enum修飾的列舉類中必須放在第一個位置。!!直接-類名(),類名()……;

程式碼如下:(還可以用匿名內部類實現方法)

package com.bigdat.java.day19;
interface Play{
    void fun();
}
enum Season2 implements Play{
    SPRING("Spring","春意黯然"){
        @Override
        public void fun() {
            System.out.println("看我像不像匿名內部類");
        }
    },
    SUMMER("Summer","夏日炎炎"){
        @Override
        public void fun() {

        }
    },
    AUTUMN("Autumn","碩果累累"){
        @Override
        public void fun() {

        }
    },
    WINTER("Winter","寒風凌冽"){
        @Override
        public void fun() {

        }
    };

    private final String SEASON_NAME;
    private final String SEASON_DESC;

    private Season2(String SEASON_NAME, String SEASON_DESC) {
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }

    public String getSEASON_NAME() {
        return SEASON_NAME;
    }

    public String getSEASON_DESC() {
        return SEASON_DESC;
    }
}
public class EumnDemo3 {
    public static void main(String[] args) {
        Season2 spring = Season2.SPRING;
        System.out.println(spring.getSEASON_DESC()+"--------"+spring.getSEASON_DESC());
        spring.fun();

    }
}