Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Enum-value without using Enum-classname

I use a static enum in an interface and want to use it in an extending class.

I have following interfaces:

public interface StateSupport {
    public static enum State {
        NEW,
        UNCHANGED,
        UPDATED;
    }
}

and

public interface Support extends StateSupport  {
    public void do(Context arg0);
}

and finally a class

public class MyClassUtil implements Support {
    public void do(Context arg0){ 
        MyClass obj = new MyClass(NEW);
    }

}

The point is that I dont want to write "State.NEW", just "NEW" :-)

So how can it do that without using the enum name. Is there a way at all?

like image 793
Randbedingung Avatar asked Nov 16 '12 11:11

Randbedingung


People also ask

Can enum be used as variable value?

Enumerated Type Declaration to Create a Variable Similar to pre-defined data types like int and char, you can also declare a variable for enum and other user-defined data types. Here's how to create a variable for enum.

Can I override valueOf enum Java?

Since you cannot override valueOf method you have to define a custom method ( getEnum in the sample code below) which returns the value that you need and change your client to use this method instead. getEnum could be shortened if you do the following: v. getValue().

Can we assign value to enum?

You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

Is it better to use enum or constant?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.


1 Answers

You can use a static import:

import static com.yourpackage.StateSupport.State.NEW;
import static com.yourpackage.StateSupport.State.UNCHANGED;
import static com.yourpackage.StateSupport.State.UPDATED;

or in short (discouraged):

import static com.yourpackage.StateSupport.State.*;
like image 147
Kai Avatar answered Oct 14 '22 00:10

Kai