pass objects as an argument in Java

Object as an Argument in Java

Object as an argument is use to establish communication between two or more objects of same class as well as different class, i.e, user can easily process data of two same or different objects within function.

In Java, When a primitive type is passed to a method ,it is done by use of call-by-value . Objects are implicitly passed by use of call-by-reference.

class Add
{ 
	int a;
	int b;

	Add(int x,int y)// parametrized constructor 
	{
		a=x;
		b=y;
	}
	void sum(Add A1) // object  'A1' passed as parameter in function 'sum'
	{ 
		int sum1=A1.a+A1.b;
		System.out.println("Sum of a and b :"+sum1);
	}
}

public class classExAdd
{
	public static void main(String arg[])
	{ 
		Add A=new Add(5,8);
		/* Calls  the parametrized constructor 
		with set of parameters*/
		A.sum(A);
	}
}

Output

Sum of a and b :13

reference:

https://www.includehelp.com/java/object-as-an-argument-in-java.aspx

https://www.tutorialspoint.com/can-we-pass-objects-as-an-argument-in-java

Leave a comment

Blog at WordPress.com.

Design a site like this with WordPress.com
Get started