Cute Happy Ghost
본문 바로가기
JAVA/Java

enum의 name()과 tostring()의 차이점

by JENN_tech7 2022. 1. 10.
728x90
SMALL

The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum.

Therefore, if you need the name of the field itself, use name(). If you need a string representation of the value of the field, use toString().

 

=> 쉽게 말해 tostring은 override해서 내맘대로 커스텀이 가능하다는 얘기

default 필드이름을 쓰려면 name()을 쓰세요~

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

 

 

 

출처 : https://stackoverflow.com/questions/18031125/what-is-the-difference-between-enum-name-and-enum-tostring

728x90
LIST

댓글