Java – setter method in constructor
•
Java
Get a problem I have
public class Student{
private String studentNumber;
private String studentName;
private double studentResult;
public Student (String aNumber,String aName){
setStudentNumber(aNumber);
setStudentName(aName);
setStudentResult(0);
}
// The standard getter and setter method are define here.
}
What is the purpose of using setter methods in constructors? And using setstudentresult (0), do we need another instance variable?
Solution
Calling overridable methods is an anti - pattern, which may cause problems if students are overridden A good model is to keep students unchanged
public class Student{
private final String studentNumber;
...
public Student (String studentNumber,...) {
this.studentNumber = studentNumber;
...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
