Tuesday, July 12, 2016

Object as Parameter

In Java, the object can serve as parameter from a method. So far we are only using variables with simple type as parameters that we pass into a method. In this post we will see how Java treats the object as a parameter. To simplify the discussion, here we will add a method to the class Box containing the parameter of object. The method we will use to compare the box object with each other, whether equal or not. The source code is as follows:

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);
   }

   //Define method with object Box as parameter 
   boolean isSame(Box k) {
      if ((k.length == this .length) &&
         (k.width == this.width) &&
         (k height == this.height)) {
         return true;
      } else {
  return false;
      }
   }
}

class DemoParamObject {

   public void main(String [] args) {

      Box b1, b2, b3, b4;

      b1 = new Box(4, 3, 2); 
      b2 = new Box(6, 5, 4); 
      b3 = new Box(4, 3, 2); 
      b4 = new Box(6, 5, 4);

      System.out.println ("b1 == b2 : " + b1.isSame(b2)); 
      System.out.println ("b1 == b3 : " + b1.isSame(b3)); 
      System.out.println ("b2 == b4 : " + b2.isSame(b4));
   }
}



The result will be given by the above program as follows:

b1 == b2: false
b1 == b3: true
b2 == b4: true

Method isSame() that you see above has box object as parameter. Please also be noted how to call:

b1.isSame(b2)

The above code is used to check whether the object b1 and b2 is equal to or not. If the value of both object is same, the method will return true. Otherwise, the value to be returned is false.

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 Dwarka

    ReplyDelete