Java Reference
In-Depth Information
the main method is static, it can only call static methods in the same class. This is the
template that we have seen before this chapter.
6.3 Default Constructor
Next, let us examine how the outside world can interact with a class through its interface
(i.e., public methods). The following code creates a die, rolls it, and prints its value.
Die d = new Die () ;
d. rollDie() ;
System. out . println (d. getValue () ) ;
The new keyword is used to create a new object. As is the case with arrays, new returns
a reference to the object. Java actually treats arrays as special types of objects that support
the index operation through the use of the square brackets syntax.
Note that the new keyword returns a reference to an object that does not change during
the life of an object. Alternatively, the address of an object can change as the object is
moved. However, this distinction is beyond of the scope of this topic and does not affect the
way in which we write our programs. Therefore, for simplicity, we assume that new returns
the address of an object and this address does not change during the life of the object.
The first line in the above code can be split into two lines.
Die d;
d= new Die () ;
Thefirstlinedefinesthevariable d to be of type Die , while the second line creates a new
object and makes d point to it; see Figure 6.2. You may have noticed that the parentheses
after Die look as though we are calling a method and this is not far from truth.
Every class has one or more constructor methods (or constructors for short). The
purpose of a constructor is to instantiate a new object of the class. If a constructor is
not defined for a class (e.g., it is not defined in the Die class), then a default constructor
that takes no arguments and that does nothing is created.
Therefore, the class Die is actually rewritten as follows by Java.
class Die {
private int dieValue ;
location 1000
dieValue = ...
d = 1000
FIGURE 6.2: Example of object.
Search WWH ::

Custom Search