-1

I have an Enum class in Airport.java

package test;

public enum Airport {
    PHX,
    LAX,
    SFO,
    NRT,
    SIN;

    Airport() {
    }
}

and a Test class in Test.java

package test;

public class Test {

    public static void main(String[] args) {
        Airport a = Airport.PHX;
        System.out.println(a);
        System.out.println(String.valueOf(a));
        System.out.println(a.name());
        System.out.println(a.toString());
        System.out.println(a.name() + '@' + Integer.toHexString(a.hashCode()));
    }

}

The output for this is

PHX
PHX
PHX
PHX
PHX@15db9742

but shouldn't the output be

PHX
PHX
PHX
PHX@15db9742
PHX@15db9742

According the the Object API https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html the default Object.toString() is getClass().getName() + '@' + Integer.toHexString(hashCode())

Tom
  • 1,343
  • 3
  • 21
  • 28

1 Answers1

5

That's indeed the default implementation of toString(). However, java.lang.Enum, the implicit base class for all enums overrides toString() by returning its name.

Mureinik
  • 277,661
  • 50
  • 283
  • 320
  • 1
    Short and simple. Also, don't forget: http://stackoverflow.com/questions/13291076/java-enum-why-use-tostring-instead-of-name. – MordechayS Oct 22 '16 at 19:06
  • @MordechayS, that post was actually the original post that sent me down the rabbit hole looking for this. – Shawn Elledge Oct 22 '16 at 19:12