KaiquanMah's picture
public void setAttributeName(dtype attributeName) { ...<chk> <set value>... }
2f66157 verified
The principle of set methods is the same as that of observation methods:
they allow the client to CHANGE the STATE of the OBJECT.
OFTEN, setting methods are of the 'void' type, since their purpose is to set the value of an attribute.
Of course, the type can be something other than void, for example, a boolean type setting method could
return true or false depending on whether the given value was allowed or not.
Consider the class ExamResult, which has a setting method for the attribute grade added to it:
Before setting the value of the attribute, it is checked that the given value is within the allowed range.
The method is named in the form setAttributeValue.
The setting is done in a familiar way from the constructor, using the keyword 'this':
class ExamResult {
// PRIVATE ATTRIBUTES
private String student;
private int grade;
//CONSTRUCTOR
public ExamResult(String student, int grade) {
this.student = student;
this.grade = grade;
}
// GET
public int getGrade() {
return grade;
}
//SET
public void setGrade(int grade) {
if (grade >= 1 && grade <= 5) {
this.grade = grade;
}
}
}
Now the client can set a new value for the rating by calling a method.
public class TestClass {
public static void main(String[] args) {
ExamResult r = new ExamResult("Ann", 3);
// SET/UPDATE ATTRIBUTE HERE
r.setGrade(5);
System.out.println(r.getGrade());
// VS
// This is not accepted, so the grade does not change
r.setGrade(-1);
System.out.println(r.getGrade());
}
}
Program outputs:
5
5
In the Student class, it would be easiest for the customer if points could be added to the regulation
by one method in addition to the given number
- often the number of credits increases by a certain value when a course is completed.
So let's implement methods in the class for both setting and adding credits.
At the same time, the other missing set and get methods are added to the class.
class Student {
private String name;
private String studentId;
private int studyPoints;
public Student(String name, String studentId, int studyPoints) {
this.name = name;
this.studentId = studentId;
this.studyPoints = studyPoints;
}
public String getName() {
return name;
}
public String getStudentId() {
return studentId;
}
public int getStudyPoints() {
return this.studyPoints;
}
public void setName(String name) {
this.name = name;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public void setStudyPoints(int studyPoints) {
if (studypoints >= 0) {
this.studypoitns = studypoints;
}
}
public void addPoints(int completionPoints) {
if (completionPoints >= 0) {
this.studypoints += completionPoints;
}
}
}