Java Reference
In-Depth Information
public class Student1 {
public String year;
public double grade;
}
Because the class does not implement tight encapsulation, the fi elds of a Student1 object
can take on any values. The following code is valid, although from an application point of
view the values do not make sense:
Student1 s = new Student1();
s.year = “Memphis, TN”;
s.grade = -24.5;
The string “Memphis, TN” is not a valid year, and we can assume that a student's grade
should never be negative. With tight encapsulation, these issues can easily be avoided
because users of the class cannot access its fi elds directly. By forcing a method call to
change a value, you can validate any changes to the fi elds of the object.
The following Student2 class is similar to Student1 but implements tight encapsulation. It
is not possible for year to be an invalid value or grade to be negative or greater than 105.0 :
1. public class Student2 {
2. private String year;
3. private double grade;
4.
5. public void setYear(String year) {
6. if(!year.equals(“Freshman”) &&
7. !year.equals(“Sophomore”) &&
8. !year.equals(“Junior”) &&
9. !year.equals(“Senior”)) {
10. throw new IllegalArgumentException(
11. year + “ not a valid year”);
12. } else {
13. this.year = year;
14. }
15. }
16.
17. public String getYear() {
18. return year;
19. }
20.
21. public void setGrade(double grade) {
22. if(grade < 0.0 || grade > 105.0) {
23. throw new IllegalArgumentException(
Search WWH ::




Custom Search