How to return Objects from Methods

  • 0
      Java enables us to return objects from the methods as well. Returning and passing objects need to consider the  parent child relationship among the classes. This relationship holds importance because, as a matter of fact, Object of parent class can hold the address of object of child class.
      This concept is much more utilised in the J2EE. Though the parent class can hold the address of object of child class, it can not access the methods of child class. On the contrary, child class Object can not hold the address of its parent.

The fallowing program clearly shows how to pass and return Object from a method.
package ClassIllustration;

class ReturnObject
{
 int num;
 
 ReturnObject(int num)
 {
  this.num = num;
 }
 
 ReturnObject incr(ReturnObject ro)
 {
  ro.num++;
  
  return ro;
 }

 public static void main(String args[])
 {
  ReturnObject ro = new ReturnObject(0);
  
  for(int i=0;i<10;i++)
  {
   System.out.println("Current Value of Num is " + (ro.incr(ro)).num);
  }
 }
}
Well, the program has an unusual line which is
(ro.incr(ro)).num
Let me explain the line, ro,incr(ro) is the simple call to incr() method of the ro object where ro is also being passed as an parameter. The return type is also an object, so, theoretically, for the sake of understanding, we can replace ro.incr(ro) by the object ro, now in println() statement, we simply have asked to print the value of the num instance variable.
To compile the program
javac -d . ReturnObject.java

And, to run the program
java ClassIllustration.ReturnObject
On My Computer, the output was

Current Value of Num is 1

Current Value of Num is 2

Current Value of Num is 3

Current Value of Num is 4

Current Value of Num is 5

Current Value of Num is 6

Current Value of Num is 7

Current Value of Num is 8

Current Value of Num is 9

Current Value of Num is 10

No comments:

Post a Comment