Java Reference
In-Depth Information
Related to this idea of limiting access, you can use the accessor methods to check for validity before
changing the variable's value. If an invalid value is provided, the programmer can decide how to
handle it, for example, by throwing an exception as you saw in the previous chapter. You can also
add some notifications when a change occurs, so the program reacts accordingly.
On the other hand, when retrieving values from variables, you can manage this in different ways
by using your accessor methods. You can provide “read‐only” access to a value by providing meth-
ods to return a defensive copy but not change the value. In the Product program, lots of related
classes might need to know what the price of a product is to calculate sales, tax, or profit figures, for
example. However, only a few, such as a discounting application, should be able to modify it. You
may also want to provide information that is collected or calculated from more than one variable. In
the Product program, you might create an accessor method that adds a tax or fee to the price before
returning the total price.
Finally, encapsulation can improve program maintenance by limiting the impact of changes in one
class on other related classes. In the Product program, you might need to adapt the Product class
later to accommodate more information about products or to change the representation in some
way. However, as long your displayString() still returns a String, the other classes calling this
method continue functioning as expected. If every related class printed the statements based on the
instance variables directly, a change to the Product class would require adaptations to every other
class to ensure the printing methods still functioned properly.
access modifiers
The first step to restricting access to variables or methods is to adjust the access modifiers.
These were introduced in Chapter 4, where the idea of encapsulation was mentioned but not
explained in full detail. There are four access modifiers that can be applied to methods and
variables in Java:
public : Can be accessed by any class
protected : Can be accessed by subclasses or classes in the same package
no modifier : Can be accessed by classes in the same package
private : Can be accessed only from within the same class
You can see the access levels in Figure 7-1.
Class
Package
Subclass
World
public
+
+
+
+
protected
+
+
+
no modifier
+
+
private
+
figure 7-1
 
Search WWH ::




Custom Search