1
0

More than 3 years have passed since last update.

enum class の使用例

Last updated at Posted at 2021-08-20

はじめに

今まで enum はただ定数を保管しておくためのクラスだと思っていたが、業務の中で自分が知らなかった方法で enum を使用していたし、便利だなと思ったのでメモとして残す。

Java Silver の試験には出てこなかった。

enum class

(1) enum でもコンストラクタの定義ができる。
・ ここでは引数で受け取った名前と血液型を決定

(2) メソッド getPesonInfoPesonInfo を初期化して返す。
・ この enum クラスにセットされた名前と血液型を使用して初期化したPesonInfoを返す。

package enumTest;

public enum Persons {
    // (3)
    TARO("田中太郎","AB型"),
    YUKA("佐々木優花", "O型");

    // (1)
    Persons(String name, String bloodType){
        this.name = name;
        this.bloodType = bloodType;
    }

    private String name;
    private String bloodType;

    // (2)
    public PersonInfo getPesonInfo(){
        return new PersonInfo(this.name, this.bloodType);
    }
}

PersonInfo class

名前と血液型をフィールドに、コンストラクタを持つ普通のクラス

package enumTest;

public class PersonInfo {
    private String name;
    private String bloodType;

    PersonInfo(String name, String bloodType){
        this.name = name;
        this.bloodType = bloodType;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }

    public void setBloodType(String bloodType){
        this.bloodType = bloodType;
    }

    public String getBloodType(){
        return this.bloodType;
    }
}

使用例

(3) Persons.TARO で enum class を初期化

(4) メソッドチェーンで getPesonInfo 呼び出し。
enum class に定義してある getPesonInfo の返却値の型は PersonInfo。返却されるときには既に名前と血液型はセットされている。

taroInfoには (3) で 初期化した際にセットした名前と血液型が格納

package enumTest;

public class Main {
    public static void main(String[] args) {
        // (4)
        PersonInfo taroInfo = Persons.TARO.getPesonInfo();
        System.out.println(taroInfo.getName());
        System.out.println(taroInfo.getBloodType());

        System.out.println("----------------------");

        PersonInfo yukaInfo = Persons.YUKA.getPesonInfo();
        System.out.println(yukaInfo.getName());
        System.out.println(yukaInfo.getBloodType());
    }
}

出力結果

田中太郎
AB型
----------------------
佐々木優花
O型

終わりに

既にいい記事が出ていた。。。
https://qiita.com/igm50/items/8c9788d4ba5868642c69

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0