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;
}
}
class RetOb {
public static void main(String args[]) { Test
ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a:
" + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second
increase: " + ob2.a);
}
}
The output generated by this
program is shown here:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
As you can see, each time incrByTen( ) is invoked, a new object
is created, and a reference to it is returned to the calling routine.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.