Java Reference
In-Depth Information
In the program VirtualDog.java, listed previously, the class Dog con-
tains two data items: one is a variable of type int and another one is a
string. Both are declared with the private access modifier in order to pre-
serve encapsulation, as follows:
// Class variables
private int dogNum; // Dog object number
private String dogName; // Dog object name
The class Dog provides the method setDogData() that assigns a name
and a number to each dog object created from the class. Another method,
named showDogData(), returns the name and number of a dog object.
Thus, data is encapsulated, since it is only accessible through methods in
the Dog class. Client code cannot see or alter these variables. The class
data is protected from unauthorized access.
Object variables and class variables
Object variables are declared without the static keywords. The variables
dogNumanddogName,listedpreviously,areobjectvariables.Objectvari-
ables are associated with the objects of the class. For every object
instantiated from a class there is a copy of each of the object variables.
Another type of variable is declared with the static attribute. When a
variable is of static type it is related to the class itself, not to the objects.
Class variables are used in storing information that relates to all the ob-
jects of a class, and not to any object in particular. In the program
VirtualDog, listed previously, you could have used a class variable to keep
track of the number of dog objects instantiated. The use of class variables
is discussed later in this chapter.
Building Objects
Aclass is an object factory. To build an object the class uses a special
method called a constructor. The constructor method is called whenever
an object is created. The constructor has the same name as the class. You
can write your own constructors for your classes; however, if you do not
codeaconstructor,Javasuppliesoneforyou.Theconstructorcreatedau-
tomatically by Java is sometimes called the default constructor. The only
functionperformedbythedefaultconstructoristosettoaknownstateall
objectvariablesandclassvariablesthatwerenotinitializedintheirdecla-
rations. The various variable types are initialized as follows:
1. All numeric variables are set to 0
2. All strings are set to null
Search WWH ::




Custom Search