コツコツ学習ブログ

プログラマのweb上のメモ的なもの

列挙型

列挙型(enum)とは

指定した種類の値だけを入れることのできるかた switch文にも利用できる

  • 定義 アクセス修飾子 enum 列挙型名 { 列挙子1,列挙子2,列挙子3, ... }

列挙子

列挙型の宣言では、その型の変数に入りうる具体的な値を列挙子(enum constans)として カンマで区切って宣言する

Main.java

package sample;

public class Main {
    public static void main(String[] args) {
        //列挙型をインスタンス化
        Account a1 = new Account("1222121", AccountType.FUTSU);
        System.out.println("口座番号は" + a1.getAccountNo() + "です");
        System.out.println("口座種別は" + a1.getAccountType() + "です");
    }
}
package sample;

//列挙型enum定義
public class Account {
    //フィールド宣言
    private String accountNo;
    private int zandaka;
    private AccountType accountType;

    //コンストラクタ
    public Account(String aNo, AccountType aType) {
        this.accountNo = aNo;
        this.accountType = aType;
    }

    public String getAccountNo() {
        return this.accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public int getZandaka() {
        return this.zandaka;
    }

    public void setZandaka(int zandaka) {
        this.zandaka = zandaka;
    }

    public AccountType getAccountType() {
        return accountType;
    }

}
AccountType.java

package sample;

public enum AccountType {
    FUTSU, TOUZA, TEIKI;
}