简体   繁体   中英

In the given Java code, what name() method will return?

I have enum defined as follows

public enum EventBusAddress{
   TRADE_PAIR,
   ORDER 
}

And name method is called as follows

String trade_pair = EventBusAddress.TRADE_PAIR.name();

Can someone please explain what name() method is returning?

The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration. If not declared as above it will get you toString() but result is FINAL.

Why use name ? The name() is a final method, so it cannot be overridden so its better then toString.

When you use the keyword 'enum', a class is created by it extending java.lang.Enum. One method in java.lang.Enum is 'public final String name()'. This method returns exact declaration of the enum as a String. You can override toString() and get more descriptive name if you want.

From Java Doc,

 /** * Returns the name of this enum constant, exactly as declared in its * enum declaration. * * <b>Most programmers should use the {@link #toString} method in * preference to this one, as the toString method may return * a more user-friendly name.</b> This method is designed primarily for * use in specialized situations where correctness depends on getting the * exact name, which will not vary from release to release. * * @return the name of this enum constant */ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM