1. 程式人生 > >JAVA19基礎-列舉型別

JAVA19基礎-列舉型別

列舉型別

一.對比兩種方法
利用 public static final 定義常量

public class Light {
	public static final int RED=1;
	public static final int GREEN=2;
	public static final int YELLOW=3;
}

利用列舉型別定義常量

public enum LightA {
	RED,GREEN,YELLOW
}


public enum Light {
    // 利用建構函式傳參
    RED (1), GREEN (3), YELLOW (2);
  
    // 定義私有變數
    private int nCode ;
  
    // 建構函式,列舉型別只能為私有
    private Light( int _nCode) {
      this . nCode = _nCode;
    }
  
    @Override
    public String toString() {
      return String.valueOf ( this . nCode );
    }
  }