Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling enum's method [duplicate]

Tags:

java

enums

I have the following enum:

 enum Days{
    TODAY{
        @Override
        public Date getLowerBound(){
            another();             //1
            currentUpperBound();   //2
            return null;
        }

        @Override
        public Date another() {
            return null;
        }
    };

    public abstract Date getLowerBound();

    public abstract Date another();

    private Date currentUpperBound(){
        return null;
    }
}

Why does //2 causes compile-time error with

Cannot make a static reference to the non-static method 
currentUpperBound() from the type Days

But //1 compiles fine? Both methods are non-static. I can't see any problem... Maybe it has something to do with Eclipse?

UPDATE: As @Florian Schaetz noticed in the comment, if we declare the method having static private modifier it will work fine. Why?

like image 613
St.Antario Avatar asked Aug 11 '15 08:08

St.Antario


People also ask

Can enum have two same values Java?

CA1069: Enums should not have duplicate values.

Can enum have two same values python?

Introduction to the enum aliases By definition, the enumeration member values are unique. However, you can create different member names with the same values.

What does enum GetValues return?

The GetValues method returns an array that contains a value for each member of the enumType enumeration.

How to get values from an enum?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.


1 Answers

I suggest making currentUpperBounds() protected instead of private. Another solution would be to prefix your call with super., which also works:

@Override
public Date getLowerBound(){
   another();
   super.currentUpperBound();
   return null;
}

Alternatively, TODAY also works:

@Override
public Date getLowerBound(){
   another();
   TODAY.currentUpperBound();
   return null;
}

Mick Mnemonic mentioned the excellent answer in this duplicate, which explains it pretty nicely.

like image 102
Florian Schaetz Avatar answered Sep 18 '22 06:09

Florian Schaetz