Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum static or non-static method

Tags:

java

enums

static

Consider the following enum class

public enum ClassA {
    CHECK1("X", 0),
    CHECK2("Y", 2),
    CHECK3("Z", 1);

    private final String id;
    private final String cdValue;

    private ClsA(String id, String cdValue) {
        this.id = id;
        this.cdValue = cdValue;
    }

    private String getId() {
        return id;
    }

    private String getCdValue() {
        return cdValue ;
    }

    private static final List<String> cdValues = new ArrayList<String>();

    static {
        for (ClassA clsA : ClassA.values()) {   
            cdValues.add(clsA.getCdValue());    
        }
    }   

    public boolean isCdValue(String cdValue)
    {
        if clsValues.contains(cdValue)
            return true;
        else return false;
    }   
}

The question that I have is does the method isCdValue has to be static. I have to use this method isCdValue for every input given by the client. Therefore the method parameter cdValue changes for every input.

If it cannot be static then I would like to know how I can access this method. Please note I am primarily interested in learning about static of non-static method call. If it is a non-static call in a enum then how can we call this non static method. I am not trying to resolve the issue of how to get about checking the cdValue exists or not. It is just an example.

like image 551
none none Avatar asked Oct 18 '13 09:10

none none


People also ask

Are enum methods static?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

Can enum have non static methods?

PHP enums (both pure enums and backed enums) can have: static Methods; Non-Static Methods.

Is enum always static?

As enums are inherently static , there is no need and makes no difference when using static-keyword in enums . If an enum is a member of a class, it is implicitly static.

Are enums static by default?

Yes, enums are effectively static.


1 Answers

does the method isCdValue has to be static.

Yes, the method isCdValue has to be static here. An enum is a special kind of class. An enum constant defines an instance of the enum type. An enum type has no instances other than those defined by its enum constants. Hence new can not be used to instantiate an enum.

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1).

Refer this

like image 137
Ritesh Gune Avatar answered Oct 01 '22 16:10

Ritesh Gune