Java Reference
In-Depth Information
In Java, fields can also be declared private or public. So far, we have not seen examples of
public fields, and there is a good reason for this. Declaring fields public breaks the information-
hiding principle. It makes a class that is dependent upon that information vulnerable to incorrect
operation if the implementation changes. Even though the Java language allows us to declare
public fields, we consider this bad style and will not make use of this option. Some other object-
oriented languages do not allow public fields at all.
A further reason for keeping fields private is that it allows an object to maintain greater control
over its state. If access to a private field is channeled through accessor and mutator methods,
then an object has the ability to ensure that the field is never set to a value that would be incon-
sistent with its overall state. This level of integrity is not possible if fields are made public.
In short, fields should always be private.
Java has two more access levels. One is declared by using the protected keyword as access
modifier; the other one is used if no access modifier at all is declared. We shall discuss these in
later chapters.
Learning about classes from their interfaces
We shall briefly discuss another project to revisit and practice the concepts discussed in this
chapter. The project is named scribble , and you can find it in the Chapter 5 folder of the topic
projects. This section does not introduce any new concepts, so it consists in large part of exer-
cises, with some commentary sprinkled in.
5.12.1 The scribble demo
The scribble project provides three classes: DrawDemo , Pen , and Canvas (Figure 5.4).
Figure 5.4
The scribble project
The Canvas class provides a window on screen that can be used to draw on. It has operations
for drawing lines, shapes, and text. A canvas can be used by creating an instance interactively
Search WWH ::

Custom Search