Java - Passing objects as arguments to methods

Java

Share

In this tutorial we will learn how to pass objects as arguments in Java programming language.

We can pass object like any other variable as argument to a method in Java.

It is assumed that you know how to instantiate an object from a class. Feel free to check out the previous tutorial to recap.

Example

In the following example we are instantiating objects of the Cube class. And we are checking if two objects are equal by comparing the length of their side.

class Cube {

  // member variable
  private double side;

  // constructor
  Cube(double side) {
    this.side = side;
  }

  // this method will check
  // if two cubes are equal
  public boolean isEqual(Cube obj) {
    if (this.side == obj.side) {
      return true;
    }
    else {
      return false;
    }
  }
}

class ObjectArgumentExample {
  public static void main(String[] args) {
    // create 3 cubes
    Cube cube1 = new Cube(10);
    Cube cube2 = new Cube(12);
    Cube cube3 = new Cube(10);

    // check equal cubes
    if (cube1.isEqual(cube2)) {
      System.out.println("Cube 1 is equal to Cube 2");
    }

    if (cube1.isEqual(cube3)) {
      System.out.println("Cube 1 is equal to Cube 3");
    }

    if (cube2.isEqual(cube3)) {
      System.out.println("Cube 2 is equal to Cube 3");
    }
  }
}

Output:

$ javac ObjectArgumentExample.java 
$ java ObjectArgumentExample
Cube 1 is equal to Cube 3

So, in the above code we are passing object of class Cube to the method isEqual which validates if two cubes are equal or not. If they are equal then the method isEqual returns true otherwise, false.

So, in the above example we can see that cube1 is equal to cube3 as both have side equal to 10.

Share

Recently Updated