img
height = h;
depth = d;
}
}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
As you can see, the setDim( ) method is used to set the dimensions of each box. For
example, when
mybox1.setDim(10, 20, 15);
is executed, 10 is copied into parameter w, 20 is copied into h, and 15 is copied into d. Inside
setDim( ) the values of w, h, and d are then assigned to width, height, and depth, respectively.
For many readers, the concepts presented in the preceding sections will be familiar.
However, if such things as method calls, arguments, and parameters are new to you, then you
might want to take some time to experiment before moving on. The concepts of the method
invocation, parameters, and return values are fundamental to Java programming.
Constructors
It can be tedious to initialize all of the variables in a class each time an instance is created. Even
when you add convenience functions like setDim( ), it would be simpler and more concise
to have all of the setup done at the time the object is first created. Because the requirement
for initialization is so common, Java allows objects to initialize themselves when they are
created. This automatic initialization is performed through the use of a constructor.
A constructor initializes an object immediately upon creation. It has the same name as the
class in which it resides and is syntactically similar to a method. Once defined, the constructor
is automatically called immediately after the object is created, before the new operator completes.
Constructors look a little strange because they have no return type, not even void. This is
because the implicit return type of a class' constructor is the class type itself. It is the constructor 's
job to initialize the internal state of an object so that the code creating an instance will have
a fully initialized, usable object immediately.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home