gpt4 book ai didi

java - Java 枚举常量应该通过 "get"方法或公共(public)最终字段或两者来检索吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:48:03 27 4
gpt4 key购买 nike

例如下面的代码:

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。它们是实例字段。

您的代码是正确的。您可能希望将您的字符串字段标记为 final 并摆脱 setXXX 方法(因为 Enum 值传统上是不可变的)。

关于java - Java 枚举常量应该通过 "get"方法或公共(public)最终字段或两者来检索吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213760/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com