Write a Java program to pass an object as an argument


The program consists of two classes: PassObject and Sample. PassObject creates two instances of Sample class and sets their num values. It then calls the add_Object method of o1 and passes o2 as an argument. This method adds the value of num of o1 and num of o2 and returns the sum. The sum is then printed to the console.

The Sample class has two fields: num and a setter method setNum that sets the value of num. It also has a method add_Object that takes an object of Sample class as an argument, adds the value of num of both the objects and returns the sum.

Source Code

class PassObject
{
	public static void main(String args[])
	{
		Sample o1 = new Sample();
		Sample o2 = new Sample();
		o1.setNum(10);
		o2.setNum(20);
 
		int res = o1.add_Object(o2);
		System.out.println("Addition : " + res);
	}
}
class Sample
{
	int num;
	void setNum(int n)
	{
		num = n;
	}
	int add_Object(Sample obj)
	{
		int add = 0;
		add = num + obj.num;
		return add;
	}
}

Output

Addition : 30