0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】Enum(列挙型)の使い方

Last updated at Posted at 2021-03-07

#Enum(列挙型)とは?
Enum(列挙型)とは、**複数の定数をひとつにまとめておくことができる型**のことで、
指定した種類の値のみ格納できます。

#定義方法
列挙型で定義する具体的な値を**列挙子**と呼び、カンマで区切って宣言します。


アクセス修飾子 enum 列挙名 {列挙子1, 列挙子2, 列挙子3,・・・};

#使い方


package animal;

enum Animals {
    DOG,
    CAT,
    TIGER,
}

public class Animal {
    public static void main(String[] args) {
    	animalName.outputAnimalName(Animals.TIGER);
    }
}

class animalName {
	static void outputAnimalName(Animals animal){
    	if(animal == Animals.DOG) {
    		System.out.println("イヌです");

    	}else if(animal == Animals.CAT) {
    		System.out.println("ネコです");

    	}else if (animal == Animals.TIGER){
    		System.out.println("トラです"); //-> トラです
    	}
	}
}

列挙型の定数に値を設定する方法


package animal;

public enum Animals {
    DOG(1),
    CAT(2),
    TIGER(3);

    private int animalNum;

    private Animals(int num){
        this.animalNum = num;
    }

    public int getAnimalNumber(){
        return animalNum;
    }
}

public class Test1 {
    public static void main(String[] args) {

        System.out.println(Animals.DOG.getAnimalNumber()); // 1
        System.out.println(Animals.CAT.getAnimalNumber()); // 2
        System.out.println(Animals.TIGER.getAnimalNumber()); // 3
    }
}

#参照
【Java 入門】Enum(列挙型)の使い方総まとめ

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?