Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Java enum constants be retrieved through "get" methods or public final fields or both?

Tags:

java

enums

See below code for example:

public enum Employees {  

    BOB("Bob Barker", "BB", 100);    

    private String fullName; //are these better accessed through public or getFullName() below? 
    private String initials;
    private String age;  

    Employees(String fullName, String initials, int age) {  
        this.fullName = fullName;
        this.initials = initials;
        this.age = age;
    }  

    public String getFullName() {  
        return fullName;
    }  
    //etc ...
}

Which method of accessing more correct or more memory efficient?

like image 714
CompSci-PVT Avatar asked Sep 15 '26 17:09

CompSci-PVT


2 Answers

You cannot access the fullName through a static method. They are instance fields.

Your code is correct. You may wish to mark your String fields as final and rid yourself of the setXXX methods (since Enum values are traditionally immutable).

like image 77
Duncan Jones Avatar answered Sep 17 '26 07:09

Duncan Jones


I would always make enum fields final, which then removes the utility of a setter. The enum instance is publicly shared and it is expected to be immutable by most sensible client code.

As far as the getter is concerned, that's up to your personal taste, although convention has it to add a getter and make the field private. So your taste has to be "strong".

like image 31
Lukas Eder Avatar answered Sep 17 '26 06:09

Lukas Eder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!