【发布时间】:2025-11-29 09:25:01
【问题描述】:
我的 Person 类中有一个 (boolean)hasDriverLicence 变量。我创建了 getter 和 setter 方法,并在 person 构造函数中使用了 hasDriverLicence,但我的 eclipse 说“未使用字段 Person.hasDriverLicence 的值”。这是代码:
public Person(int id, String firstName, String lastName, String gender, Calendar birthDate, String maritalStatus,
String hasDriverLicence) throws Exception {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
setGender(gender);
setMaritalStatus(maritalStatus);
setHasDriverLicence(hasDriverLicence);
这里是getter和setter:
public void setHasDriverLicence(String hasDriverLicence) throws Exception {
if (!(hasDriverLicence.equalsIgnoreCase("Yes")) && !(hasDriverLicence.equalsIgnoreCase("No")))
throw new Exception("Wrong input, please type Yes or No");
if (hasDriverLicence.equalsIgnoreCase("Yes")) {
this.hasDriverLicence = true;
}
else if (hasDriverLicence.equalsIgnoreCase("No")) {
this.hasDriverLicence = false;
}
}
public String getHasDriverLicence() {
if (this.hasDriverLicence = true)
return "Yes";
if (this.hasDriverLicence = false)
return "No";
else
return "";
}
【问题讨论】:
-
不确定我是否应该以拼写错误的形式关闭,但我的回答比评论长一点。如果有人费心找到一个,可能也会有一个 gazillon 欺骗。
-
仅作记录:“有驾驶执照”应该是布尔值,而不是字符串。当该字段为真时,您想要打印“是”的事实与格式有关。您的代码将其混合在一起。格式应该存在于不同的位置,并且如前所述:该字段应该具有布尔类型!
-
FWIW,只需从
getHasDriverLicence()制作一个单行线 -->return this.hasDriverLicense ? "Yes" : "No"; -
请勿使用
Exception,除非您有需要它的现有 API 合约。IllegalArgumentException是这里的正确选择。
标签: java class constructor boolean getter-setter