8.3 Returning Objects from Methods

Like any other data datatype, a method can returns object. For example, in the following program, the makeTwice( ) method returns an object in which the value of instance variable is two times than it is in the invoking object.

Program (Sample.java)

/**
 * This program demonstrates how a method can return
 * a reference to an object.
 */
public class Sample
{
   private int value;

   public Sample(int i)
   {
      value = i;
   }

   /**
    * The makeTwice method returns a Sample object
    * containing the value twice the passed to it.
    */
   public Sample makeTwice()
   {
      Sample temp = new Sample(value * 2);

      return temp;
   }

   public void show()
   {
      System.out.println("Value : " + value);
   }
}

Program (ReturnObjectDemo.java)

public class ReturnObjectDemo
{
   public static void main(String[] args)
   {
      Sample obj1 = new Sample(10);
      Sample obj2;

      // The makeTwice method returns a reference
      obj2 = obj1.makeTwice();
      obj2.show();
   }
}
          

Output :

Value : 20