Java Reference
In-Depth Information
is instance of the Person class. Do not forget that object variables always start with a
lowercase letter, while class names always start with a capital letter.
Instance variables are associated with the objects of a class. Every instance of a
class can have different values for the instance variables.
For example, we can create a new person as follows.
Person p2 = new person( "Bob" );
Now p1 and p2 are two objects of the Person class that have a different value for the
instance variable name . An instance variable of a class is a variable that is associated with
every object of the class. For example, if there are 100 objects of type Person , then 100
variables name will be created, one for every object.
6.2 Class Interaction and Data Encapsulation
Let us revisit the Yahtzee game from the previous chapter, but this time build a better
design that utilizes the object-oriented paradigm. When creating an object-oriented solu-
tion, we try to build classes and objects that model real-world entities. For example, if
we are building bank software, then we may identify the classes: BankAccount , Customer ,
Teller , and so on. The customer Peter is an example of an object that belongs to the
Customer class.
If we go back to the Yahtzee game, a die is an example of a real-world entity that we
would like to model. We will create a Die class, where a particular die will be an object (or
instance) of the class. The pillar of every class is its data. The data inside a class represents
the variables of each object in the class. In our case, every die has a dieValue that is an
integer. Next, the methods of the class need to be identified. Usually, only methods that
access or manipulate the data of the class belong to the class. In our case, this can be a
method that sets and a method that reads the value of the die. A first iteration of the Die
class follows.
class Die {
private int dieValue ;
public void setValue( int value) {
dieValue = value ;
} public int getValue () {
return dieValue ;
The variable dieValue is defined as a private variable. This means that it is only
accessible inside the class in which it is defined. Nobody outside the Die class knows about
its existence. The setValue and getValue methods are defined as public . This means that
they can be accessed from everywhere in our program.
Search WWH ::

Custom Search