o.b /= 2;
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
As you can see, in this case, the actions inside meth( ) have affected the object used as an
As a point of interest, when an object reference is passed to a method, the reference itself
is passed by use of call-by-value. However, since the value being passed refers to an object,
the copy of that value will still refer to the same object that its corresponding argument does.
REMEMBER  When a primitive type is passed to a method, it is done by use of call-by-value. Objects
are implicitly passed by use of call-by-reference.
Returning Objects
A method can return any type of data, including class types that you create. For example, in
the following program, the incrByTen( ) method returns an object in which the value of a is
ten greater than it is in the invoking object.
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks