![](/img/trans.png)
[英]Should I name final `Atomic…` member fields as constants (in all uppercase) per Java conventions?
[英]Should Java enum constants be retrieved through “get” methods or public final fields or both?
請參閱以下代碼,例如:
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 ...
}
哪種方法訪問更正確或更高效的內存?
您無法通過static
方法訪問fullName
。 它們是實例字段。
你的代碼是正確的。 您可能希望將String字段標記為final
並擺脫setXXX
方法(因為Enum
值傳統上是不可變的)。
我總是將enum字段設為final
,然后刪除setter的實用程序。 enum
實例是公開共享的,並且預期最合理的客戶端代碼是不可變的。
就吸氣劑而言,這取決於您的個人品味,盡管慣例是添加吸氣劑並使該領域保密。 所以你的品味必須“強大”。
使用getter它的約定......如果你以后使用jstl / el中依賴於使用getters /的bean規范的enum,你就不會得到任何令人討厭的驚喜。
我認為你誤解了枚舉的概念。 枚舉是一個不會改變的共享實例。 您描述的是一個常規的可變Java對象。 所以你應該做的第一件事是從enum
切換到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 ...
}
然后像普通班一樣使用你的班級:
Employee bob = new Employee("Bob Barker", "BB", 100);
編輯
你現在已經刪除了你的二傳手,但是,這對我來說仍然不像一個enum
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.