setter 方法由于此关键字而出错
setter method giving an error due to this keyword
程序在 setter 方法中抛出错误,可能是由于使用了此关键字。为什么会报错?
错误:方法调用 setAge(-5),将字段值设置为“-5”但“0”为 expected.expected:<0> 但为:<-5>。
public class Person {
private String firstName;
private String lastName;
private int age;
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public int getAge(){
return this.age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(int age){
**if(age < 0 || age > 100){
this.age = 0;** *Why this keyword gives an error here?*
}
this.age = age;
}
}
将您的设置年龄函数更改为:
public void setAge(int age){
if(age < 0 || age > 100){
this.age = 0;
}
else
this.age = age;
}
或
public void setAge(int age){
if(age < 0 || age > 100){
age = 0;
}
this.age = age;
}
程序在 setter 方法中抛出错误,可能是由于使用了此关键字。为什么会报错?
错误:方法调用 setAge(-5),将字段值设置为“-5”但“0”为 expected.expected:<0> 但为:<-5>。
public class Person {
private String firstName;
private String lastName;
private int age;
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public int getAge(){
return this.age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(int age){
**if(age < 0 || age > 100){
this.age = 0;** *Why this keyword gives an error here?*
}
this.age = age;
}
}
将您的设置年龄函数更改为:
public void setAge(int age){
if(age < 0 || age > 100){
this.age = 0;
}
else
this.age = age;
}
或
public void setAge(int age){
if(age < 0 || age > 100){
age = 0;
}
this.age = age;
}