Java Reference
In-Depth Information
//Method to return the value of x as a string
public
String toString()
{
return
(String.valueOf(x));
}
}
Consider the following statements:
IntClass firstNum =
new
IntClass();
//Line 1
IntClass secondNum =
new
IntClass(5);
//Line 2
int
num;
//Line 3
The statement in Line 1 creates the object
firstNum
and initializes it to
0
. The statement
in Line 2 creates the object
secondNum
and initializes it to
5
. The statement in Line 3
declares
num
to be an
int
variable. Now consider the following statements:
firstNum.setNum(24);
//Line 4
secondNum.addToNum(6);
//Line 5
num = firstNum.getNum();
//Line 6
The statement in Line 4 sets the value of
firstNum
(in fact, the value of the data member
x
of
firstNum
)to
24
. The statement in Line 5 updates the value of
secondNum
to
11
(the previous value
5
is updated by adding
6
to it.) The statement in Line 6 retrieves the
value of the object
firstNum
(the value of the data member
x
) and assigns it to
num
.
After this statement executes, the value of
num
is
24
.
The following statements output the values of
firstNum
and
secondNum
(in fact, the
values of their data members):
System.out.println("firstNum = " + firstNum);
System.out.println("secondNum = " + secondNum);
Table D-4 shows how variables of
int
type and the corresponding reference variables of
IntClass
type work.
TABLE D-4
Variables of
int
Type and the Corresponding Reference Variables of
IntClass
int
IntClass
Declaration
without or
with
initialization
IntClass x, y;
x =
new
IntClass();
y =
new
IntClass(5);
int
x, y
¼
5;
x
¼
24;
x.setNum(24);
Assignment
y
¼
x;
y.setNum(x.getNum());
x
¼
x + 10;
x.addToNum(10);
Addition
x
¼
x + y;
x.addToNum(y.getNum());
Search WWH ::
Custom Search