Java returning object



Returning the Object From Method

In Java Programming A method can return any type of data, including class types that you create.
For example, in the following program, the getRectangleObject( ) method returns an object.

Java Program : Returning the Object From Method

package com.pritesh.programs;

import java.io.File;
import java.io.IOException;

class Rectangle {
      int length;
      int breadth;

      Rectangle(int l,int b) {
        length = l;
        breadth = b;
      }

      Rectangle getRectangleObject() {
        Rectangle rect = new Rectangle(10,20);
        return rect;
      }
}

class RetOb {
      public static void main(String args[]) {
        Rectangle ob1 = new Rectangle(40,50);
        Rectangle ob2;

        ob2 = ob1.getRectangleObject();
        System.out.println("ob1.length : " + ob1.length);
        System.out.println("ob1.breadth: " + ob1.breadth);

        System.out.println("ob2.length : " + ob2.length);
        System.out.println("ob2.breadth: " + ob2.breadth);

        }
}

Output of the Program :

ob1.length : 40
ob1.breadth: 50
ob2.length : 10
ob2.breadth: 20

Explanation :

  1. In the above program we have called a method getRectangleObject() and the method creates object of class from which it has been called.
  2. 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.
  3. 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.