Java enum confusion

I came across the following Java code. Here the interface contains two methods, of which only one method is implemented in the enumeration. It is written that name() is executed automatically. My question is how is this possible? Previously, I did not read any rules regarding the automatic implementation of a method in enum. So what's going on here? In addition, the code does not give any 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; } } 
+6
source share
5 answers

name() defined in the Enum class that satisfies your interface contract, so you do not need to define name() unless, of course, you want to override the default behavior.

+9
source

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

This, and others, such as values() , valueOf() and ordinal() , belong to the Enum class .

+6
source

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

public final String name ()

Returns the name of this enumeration constant, exactly as specified in the enumeration declaration.

+2
source

Java has attributes and methods that are predefined for types. For enumerations, the name() method and for arrays, the length attribute are examples. In your example, the method name () will return "Mercury", "Venus", "Earth", etc.

+1
source

Each enum is kept from the abstract class Enum<E....> . This class implements both name() and the mentioned ordinal() and a few more. Take a look.

+1
source

Source: https://habr.com/ru/post/903328/


All Articles