Website For Developers

Object as Method Parameter and Return-type



Object as Method Parameter

Example

import java.util.Scanner;
//Class Start
public class ObjectParameter {
   // class variables
   int length;
   int width;

  // class constructor with two parameters
   ObjectParameter (int l, int b) {
     length = l;
     width = b;
   }

  // method that take object as a parameter
   void total(ObjectParameter r1) {
     int totalArea = r1.length * r1.width;
     System.out.println( "Total area of Rectangle \n" + totalArea);
   }

  //main method
   public static void main(String[] args) {
    // Getting user input
     Scanner scan = new Scanner(System.in);
     int length,width;

     System.out.println( "Please Enter the length of Rectangle" );
     length = scan.nextInt();
     System.out.println( "Please Enter the width of Rectangle" );
     width = scan.nextInt();

    // declaring object
     ObjectParameter object = new ObjectParameter (length, width);

    // passing object as a parameter
     object.total(object);
   } // end of main method
} // end of class

Output

Please Enter the length of Rectangle
15
Please Enter the width of Rectangle
25
Total area of Rectangle
375


Object as Return-type

Example

class Value {
   int value;

   // constructor with a parameter
   Value(int a) {
     value = a;
   }

   // Object as return type
   Value getObject() {
     Value v = new Value(10);

    // returning object
    return v;
   }
}

class HelloWorld {
   public static void main(String args[]) {
     Value obj1 = new Value(5);
     Value obj2;

     obj2 = obj1.getObject();
     System.out.println( "Value as parameters to constructor : " + obj1.value);
     System.out.println( "Value as a returning object : " + obj2.value);
   }
}

Output

Value as parameters to constructor : 5
Value as a returning object : 10