Java Reference
In-Depth Information
24. grade + “ is out of range”);
25. } else {
26. this.grade = grade;
27. }
28. }
29.
30. public double getGrade() {
31. return grade;
32. }
33. }
See if you can determine the result of the following statements:
Student2 s2 = new Student2();
s2.setYear(“Junior”);
s2.setGrade(-24.5);
Invoking setYear with the argument “Junior” changes the year fi eld to “Junior” .
Invoking setGrade with the argument -24.5 causes an IllegalArgumentException to be
thrown on line 23. Due to tight encapsulation, it is not possible for the values of Student2
to contain invalid values.
Information Hiding
One of the key benefi ts of tight encapsulation is information hiding , where the user
of an object is unaware of how the object stores its data. With information hiding and
tight encapsulation, if you ever need to alter or modify a fi eld, the users of the class are
unaffected by the change as long as you do not modify the method signatures in the
class.
For example, suppose we decide to store the grade of Student2 as a float instead of a
double . If we leave the signatures of setGrade and getGrade alone, the change will not
affect code elsewhere:
public class Student2 {
private float grade;
public void setGrade(double grade) {
if(grade < 0.0 || grade > 105.0) {
Search WWH ::




Custom Search