Java Reference
In-Depth Information
throw new IllegalArgumentException(grade + “ is out of range”);
} else {
this.grade = (float) grade;
}
}
public double getGrade() {
return grade;
}
//remainder of class definition remains unchanged...
}
The fi eld grade is now a float and a cast is needed within setGrade to assign the
double parameter to grade . Any object invoking setGrade still passes in a double , and
a double is still returned from getGrade , but behind the scenes the data is stored as a
float , and the change to the Student2 class has no effect on the code that already
interacts with Student2 objects.
The benefi ts of encapsulation outweigh any overhead of the additional method calls,
and any good OO design uses tight encapsulation in all classes. The next section discusses
another important object-oriented design concept: loose coupling.
Loose Coupling
Coupling is the extent to which one object depends on another object to achieve its goal.
For example, an Employee class might depend on an Address class to represent the home
address of an employee, so the Employee class is coupled to the Address class. At some
point in your application, your classes need to interact with each other, so you cannot avoid
coupling entirely. However, the goal of good OO design is to implement loose coupling ,
where you minimize the dependencies an object has on other objects.
If objects are tightly coupled, changing the code in one class has a major effect on the
dependent class, requiring code changes to both classes. For example, suppose we have
the following Address class:
public class Address {
public String street;
public String city;
public int zip;
}
Search WWH ::




Custom Search