Returning Objects in Java

A method can return any type of data, including class type 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

Description –

As we can see, each time incrByTen( ) is invoked, a new object is created, and a reference to it is returned to the calling routine.

The preceding program makes one more important point. Since all objects are dynamically allocated using new, you don’t need to worry about an object going out-of-scope because the method in which it was created terminates. The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no references to it, the object will be reclaimed the next time garbage collection takes place.

Content Protection by
Recommended Post   Methods in Java