Ankur Trapasiya
Ankur Trapasiya

Reputation: 2200

java enum confusion

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; }
}

Upvotes: 6

Views: 238

Answers (5)

Dave Newton
Dave Newton

Reputation: 160191

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

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

Upvotes: 6

Bala R
Bala R

Reputation: 108947

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.

Upvotes: 9

A.H.
A.H.

Reputation: 66263

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.

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 405745

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.

Upvotes: 2

belgther
belgther

Reputation: 2534

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.

Upvotes: 1

Related Questions