Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
}
like image 271
Ankur Trapasiya Avatar asked Dec 07 '11 20:12

Ankur Trapasiya


People also ask

Why enums are better than constants?

The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can enum have instance variables Java?

Enumeration is basically a list of named constant. In Java, it defines a class type. It can have constructors, methods and instance variables. It is created using the enum keyword.

Can enum have instance variables?

Enums are very powerful as they may have instance variables, instance methods, and constructors. Each enum constant should be written in capital letters. Every enum constant is by default internally public static final of type Enum declared.

How do you call an enum outside of a class?

You have to declare enum as public ... (depend on what you want) and then use class name as prefix when outside package. @RongNK - It doesn't have to be public ; if its in the same package, it can have default access. You need to use the class name as a prefix even within the same package unless you import the enum.


1 Answers

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.

like image 179
Bala R Avatar answered Sep 23 '22 18:09

Bala R