Java program to pass an object as an argument

Learn how to pass an object as an argument in Java?
Submitted by Nidhi, on March 20, 2022

Problem Solution:

In this program, we will create a Sample class. Here, we will implement a method by passing an object as an argument.

Program/Source Code:

The source code to pass an object as an argument is given below. The given program is compiled and executed successfully.

// Java program to pass an object 
// as an argument

class Sample {
  int num;

  void setNum(int n) {
    num = n;
  }

  int addObj(Sample obj) {
    int add = 0;
    add = num + obj.num;

    return add;
  }
}

class Main {
  public static void main(String args[]) {
    Sample X1 = new Sample();
    Sample X2 = new Sample();

    X1.setNum(10);
    X2.setNum(20);

    int result = X1.addObj(X2);

    System.out.println("Addition is: " + result);
  }
}

Output:

Addition is: 30

Explanation:

In the above program, we created a Sample class and public class Main.

The Sample class contains two methods setNum() and addObj(). The setNum() method is used to set the value of data member num and the addObj() method accepts an object as an argument. The addObj() method adds the value of the specified object with the current object and returns the result.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created 2 objects of the Sample class. Then we set the value of data members using the setNum() method and added the data members value using the addObj() method. After that, we printed the result.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.