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.

2 comments:

  1. Thank You for Sharing valuable information with us.

    E-Commerce is the fastest-growing platform which is becoming more demandable day by day this is a tremendous form of the vibrant sector that is bringing several opportunities to the new generation to become more skilled and professional. Taking up this great advantage in the E-Commerce sector would need the right path and the right skillset you need to learn the latest technologies and high-demand skills such as building payment gateways and developing an accessible and easy website along with the basics of E-commerce that‘s why Aptech learning official Pro E-Commerce training program in Dwarka, Janakpuri, and Gurgaon which will help to make a successful career in this booming industry. Java Programming Course helps to become an expert in Java web application development. It helps you to bring efficiency in collecting and analyzing the data through Java programming in this course you will learn effective web UI/UX design and Secure web applications by using the advanced technologies of the Java program.

    For more details please visit our website : Aptech Janakpuri

    ReplyDelete