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;
}
}
CodePudding user response:
change your set age function to :
public void setAge(int age){
if(age < 0 || age > 100){
this.age = 0;
}
else
this.age = age;
}
or
public void setAge(int age){
if(age < 0 || age > 100){
age = 0;
}
this.age = age;
}
CodePudding user response:
Use Instead
public String getFirstName(){
return firstName;
}