6

I came across the following java code. Here interface contains two methods out of which only one method is implemented in the enum. It is written that name() is implemented automatically. My question is how is it possible? I have not read any rule regarding automatic method implementation in enum before. So what is happening here? Furthermore the code is not giving any type of compile time error.

interface Named {
    public String name();
    public int order();
}

enum Planets implements Named {
    Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune;
    // name() is implemented automagically.
    public int order() { return ordinal()+1; }
}

5 Answers 5

9

name() is defined in Enum class which satisfies your interface contract so you don't have to define name() unless of course you want to override the default behavior.

Sign up to request clarification or add additional context in comments.

Comments

6

enum has a default method name(), that's all.

It, and others like values(), valueOf(), and ordinal(), come from the Enum class.

Comments

2

All enums in Java implicitly extend Enum, which implements the name() method.

public final String name()

Returns the name of this enum constant, exactly as declared in its enum declaration.

Comments

1

In Java, there are attributes and methods which are pre-defined for types. For enums, the method name() and for arrays, the attribute length are examples. In your example, the method name() would return "Mercury", "Venus", "Earth" and so on.

Comments

1

Every enum is dervided from the abstract class Enum<E....>. That class implements both name() and the mentioned ordinal() and some more. Take a look.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.