setter 方法由于 this 关键字而给出错误
程序在 setter 方法中抛出错误,可能是由于使用了 this 关键字。为什么会报错呢?
错误:方法调用 setAge(-5),将字段值设置为“-5”,但预期为“0”。预期:<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;
}
}
The program is throwing an error in the setter method possibly due to the use of this keyword. Why is it giving an error?
The error: Method call setAge(-5), set a field value of "-5" but "0" was expected.expected: <0> but was: <-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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将您的设置年龄函数更改为:
或
change your set age function to :
or