Tuesday, July 12, 2016

Object as Return Value

Object also can be used as return value on a method. Here is an example of a program that will demonstrate the concept:
class Box {
   double length;
   double width;
   double height;

   Box(double l, double w, double h) {
      length = l;
      width = w;
      height = h;
   }

   double calculateVolume() {
      return (length * width * height);
   }

   //Method that return object box
   Box enlarge(int size) {
      Box temp = new Box(length * size, width * size, height * size);
      return temp;
   }
}

class DemoReturnObject {
   
   public static void main(string[] args) {
      
   Box originalBox, newBox:

      originalBox = new Box(4, 3, 2);

      newBox =  originalBox.enlarge(2);

      System.out.println("originalBox object value"); 
      System.out.println("length: " + originalBox.length); 
      System.out.println("width: " + originalBox.width); 
      System.out.println("height: " + originalBox.height); 
      System.out.println("Volume: " + originalBox.calculateVolume());

      System.out.println("newBox object value"); 
      System.out.println("length: " + newBox.length); 
      System.out.println("width: " + newBox.width); 
      System.out.println("height: " + newBox.height); 
      System.out.println("Volume: " + newBox.calculateVolume());
   }
}



The above program will give the following result:

originalBox object value
length: 4.0
width: 3.0
height: 2.0
Volume: 24.0

newBox object value
length: 8.0
width: 6.0
height: 4.0
Volume: 192.0

As you can see above that method enlarge() will return an object box with length, width, and height two times larger than its original object.

1 comment: