1

The following simple code snippet uses the interface Named containing two methods namely name() and order() which is being implemented by enum named Days. The enum Days doesn't allow to implement the name() method of its implementing interface. Doing so, causes a compile-time error and although the name() method is not implemented by the enum, it doesn't issue any error.

package enumpkg;

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

enum Days implements Named
{
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;

    public int order()
    {
        return ordinal()+1;
    }
}

final public class Main
{
    public static void main(String[] args)
    {
        System.out.println("Monday    = "+Days.Monday.order());
        System.out.println("Tuesday   = "+Days.Tuesday.order());
        System.out.println("Wednesday = "+Days.Wednesday.order());
        System.out.println("Thursday  = "+Days.Thursday.order());
        System.out.println("Friday    = "+Days.Friday.order());
        System.out.println("Saturday  = "+Days.Saturday.order());
        System.out.println("Sunday    = "+Days.Sunday.order());
    }
}

The code works without implementing the name() method in enum. How?


The output is quite obvious as shown below.

Monday    = 1
Tuesday   = 2
Wednesday = 3
Thursday  = 4
Friday    = 5
Saturday  = 6
Sunday    = 7
4
  • 3
    What error do you get? Did you read it? Commented Dec 23, 2011 at 1:30
  • 1
    I agree with SLaks - it is very important to actually read compilation error messages, and try and understand what they are telling you. Commented Dec 23, 2011 at 1:38
  • It indicates that the overridden method name() is final and can not be overridden. Commented Dec 23, 2011 at 1:39
  • I start to think the gcc devs were on to something when they made their error messages unreadable - wasted effort to try to create good, meaningful error messages :( Commented Dec 23, 2011 at 2:34

2 Answers 2

8

The base Enum class already has a name() method.
Since this method is final, you can't override it (as the error message clearly states).

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

Comments

3

From the Java API, name() is defined as:

public final String name()

Thus name() exists for all enums, and is not overridable.

See also: Java API for enum

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.