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; }
}
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With