class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// 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);
The output from this program is shown here:
Volume is 3000.0
Volume is 162.0
As you can see, each object is initialized as specified in the parameters to its constructor.
For example, in the following line,
Box mybox1 = new Box(10, 20, 15);
the values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object.
Thus, mybox1's copy of width, height, and depth will contain the values 10, 20, and 15,
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. this can be used inside any method to refer to the current object. That is,
this is always a reference to the object on which the method was invoked. You can use this
anywhere a reference to an object of the current class' type is permitted.
To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
This version of Box( ) operates exactly like the earlier version. The use of this is redundant,
but perfectly correct. Inside Box( ), this will always refer to the invoking object. While it is
redundant in this case, this is useful in other contexts, one of which is explained in the next
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks