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?
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).
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".
使用getter它的约定......如果你以后使用jstl / el中依赖于使用getters /的bean规范的enum,你就不会得到任何令人讨厌的惊喜。
I think you are misunderstanding the concept of enums. An enum is a shared instance that does not change. What you describe is a regular mutable Java object. So the first thing you should do is switch from enum
to class
:
public class Employee {
private String fullName;
private String initials;
private String age;
public Employee(String fullName, String initials, int age) {
this.fullName = fullName;
this.initials = initials;
this.age = age;
}
public String getFullName() {
return fullName;
}
//etc ...
}
Then use your class like a regular class:
Employee bob = new Employee("Bob Barker", "BB", 100);
Edit
You have removed your setter now, but still, this still does not look like an enum
to me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.