Java Reference
In-Depth Information
Two of the compiler errors stem from the retailPrice field and the setRetail-
Price() method of DVDPlayer, both of which are private. Neither of the fol-
lowing two statements compiles:
z.setRetailPrice(199.99);
z.retailPrice = 199.99;
A DVDPlayer object has a field named retailPrice and a method setRetail-
Price(), but making them private hides them in the class, not allowing access to
them by any other class.
There seems to be a design flaw with DVDPlayer; the DVDPlayer class does
not change retailPrice from its initial value of zero, and no one else can change
or view the retailPrice field. Making a field private and hiding it in the class is
a common OOP practice known as encapsulation (discussed in the next sec-
tion), and has many positive side effects. Encapsulation, however, typically
involves adding public methods that allow the field to be viewed or changed,
something our DVDPlayer class does not contain.
A class can also have an access specifier. The only two access specifiers
that can be used for a class are public and the default. Every class we
have seen up until now has been declared. A public class can be used by
any other class. A class with the default access can only be used by other
classes in the same package.
Encapsulation
Encapsulation is the technique of making the fields in a class private and pro-
viding access to the fields via public methods. If a field is declared private, it
cannot be accessed by anyone outside the class, thereby hiding the fields within
the class. For this reason, encapsulation is also referred to as data hiding.
Encapsulation is one of the four fundamental OOP concepts. The other
three are inheritance, polymorphism, and abstraction.
The SalesPerson class in the following code demonstrates encapsulation.
Each of its fields is marked private, and there are public methods to access the
fields. The get methods that allow a field to be viewed are known as accessor
methods. The set methods that allow a field to be changed are known as muta-
tor methods.
Search WWH ::




Custom Search