Java Reference
In-Depth Information
Benefits of Encapsulation
There are many benefits of encapsulation, including:
The fields of a class can be made read-only or write-only, as was done
with the id field in the SalesPerson class. There is no way to change the
id field of a SalesPerson object after the object has been instantiated.
■■
A class can have total control over what is stored in its fields. The Sales-
Person class demonstrates this with the commissionRate field, which
can only be a value between 0.0 and 0.20.
■■
The users of a class do not know how the class stores its data. A class
can change the data type of a field, and users of the class do not need to
change any of their code.
■■
Let me demonstrate that last benefit of encapsulation with the SalesPerson
class. Notice that the commissionRate field is a double. Because it only can be
a value between 0.0 and 0.20, there is no reason we couldn't have used a float;
however, changing the data type of a field can have serious repercussions on
any other class that relies on the commissionRate field.
Because we used encapsulation, we can change the commissionRate field
to a float, and no existing code elsewhere will be affected or need to be
changed (or even recompiled, for that matter). The users of the SalesPerson
class did not know that the commissionRate was stored as a double
because the field is hidden in the class.
The only thing the users of SalesPerson know is that setCommissionRate()
takes in a double and getCommissionRate() returns a double. As long as
we leave the signatures of these two methods alone, existing code that
invokes these methods does not need to be modified.
The following code shows a modified SalesPerson class with the commission-
Rate changed from a double to a float. Notice that we did not change the
signatures of any of the methods. The only changes made were within the
setCommissionRate() method with the statement:
commissionRate = (float) newRate;
The cast operator was added to cast the incoming double to a float because
the commissionRate field is now a float.
public class SalesPerson
{
private float commissionRate; //Changed to a float
public void setCommissionRate(double newRate)
{
Search WWH ::




Custom Search