Home | | Web Programming | Returning Objects - Java

Chapter: Java The Complete Reference : The Java Language : A Closer Look at Methods and Classes

Returning Objects - Java

A method can return any type of data, including class types that you create.

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.

The preceding program makes another 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.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Language : A Closer Look at Methods and Classes : Returning Objects - Java |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.