Google+

80. Returning Objects






A method can return any type of data, including the objects.

In the following program, the incrByTen( ) method returns an object in which the value of variable a is ten greater than it is in the invoking object.

Syntax -

public ClassName MethodName( )
{
      return object;

}

Lets implement this on Eclipse IDE:

1. Launch Eclipse IDE, Create a new Java Class 'Seventh Project, Create 'Test' class as shown below:



2. Declare an instance variable 'a' as integer type as shown below:



3. Create a Test( ) constructor which receives an integer value as a parameter and assigns the received value to instance variable 'a' of Test class as shown below:



4. Create a method incrByTen( ) which returns object after incrementing the value of instance variable 'a' by 10 as shown below and save:



5. Create a class named 'ReceiveObjects' as shown below:



6. Create two objects, initialize one object 'object1' during its creating by passing a value '10' and just create another object 'object2' without initializing it as shown below:



7. Print the value of instance variable 'a' of 'object1' before calling incrByTen( ) method as shown below:



8. Call the incrByTen( ) method using 'object1' object  and store the object  returned by incrByTen() method in another object 'object2' as shown below:



9.Print the value of variable 'a' of 'object2' as shown below:



10. Call the incrByTen( ) method using 'object2' object  and store the object  returned by incrByTen() method into 'object2' as shown below:



11. Print the value of variable 'a' of  'object2' as shown below:



12. Save and Run the 'ReceiveObjects' class as shown below:


13. Observe that the output is displayed in the console as shown below:



Download this project:

Click here to download the project containing 'Test' and 'ReceiveObjects' class files used in this post (You can download the project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

'Recursion' concept will be explained in next post.



No comments: