Java Reference
In-Depth Information
private int zip;
public void setStreet(String s) {
street = s;
}
public void setCity(String c) {
city = c;
}
public void setZip(int z) {
zip = z;
}
}
The following
Employee2
class is similar to
Employee
from earlier except that it changes
the fi elds of
Address2
via
public
mutator methods:
public class Employee2 {
private Address2 home;
public Employee2(String street, String city, int zip) {
home = new Address2();
home.setStreet(street);
home.setCity(city);
home.setZip(zip);
}
}
If the
city
fi eld of
Address
is changed from a
String
to a
StringBuffer
, no changes
need to be made to the
Employee2
class as long as the signature of
setCity
is unchanged. In
this situation, the benefi t of loose coupling is achieved by using tight encapsulation.
One other design technique for achieving loose coupling involves minimizing the
interaction between two objects. For example, in the constructor of
Employee2
, several
methods are invoked on
Address2
to initialize its fi elds. A better, loosely coupled design is
to perform the initialization steps in one method call, such as a constructor. For example,
suppose we add the following constructor to
Address2
:
public Address2(String s, String c, int z) {
street = s;
city = c;
zip = z;
}
Search WWH ::
Custom Search