Passing Parameters - Programmers Heaven

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# Passing Parameters

Posts: 2Member
Hi,
I am a newbie and would appreciate it if someone could help me with the following code that I found on an online tutorial.
Thanks in advance,
Gus

class PassObj
{
int n1;
int n2;
// constructor
PassObj()
{
n1 = 0;
n2 = 0;
}

PassObj(int p1, int p2)
{
n1 = p1;
n2 = p2;
}

void multiply(PassObj p1)
{
int temp;
temp = p1.n1 * p1.n2;
System.out.println("Multiplication is " + temp);
}
public static void main(String args[])
{
PassObj obj1 = new PassObj(5,6);
PassObj obj2 = new PassObj();
obj2.multiply(obj1);
}
}

This is a program I got from a Java tutorial online. If I give my understanding of it could someone please tell me if I am correct or tell me where I have gone wrong. I am a newbie so all help is greatly appreciated.

1. The class PassObj has two int variables n1 & n2.
2. These as initialised to zero.
3. In Main, there are 2 instances of the class PassObj created. These are obj1 & obj2.
4. The multiply method is called with parameters 5 & 6 passed to it. The multiplication is done and the result is shown in the console.
My main issues are what is the point of:

PassObj(int p1, int p2)
{
n1 = p1;
n2 = p2;
}
and does the instantiation PassObj obj1 = new PassObj(5,6); actually pass parameters to the above constructor.

## Comments

• Posts: 2Member
Hey Gus,
You've pretty much got it down, the only thing is that this is an example of what we call overloaded constructors. All that means is that when you create an object of the class PassObj, there are two ways to create it.

The first doesn't require you to pass in any parameters, this is the default constructor. The other requires two integer parameters, this is the overloaded constructor.

What we have in the main method is two PassObj objects being created, one with the parameters (5, 6), the other as a default. Then the first object is passed into the multiply method of the second object which prints out the product of 5 and 6.

I don't know why they coded it this way as it unnecessarily creates an extra unneeded object who's only role is to be used as a multiplier but that's what it is.

Hope this helped,
Onepphire
• Posts: 55Member
edited December 2013

`PassObj obj1 = new PassObj(5,6);` Yes, you pass the parameters 5,6 to the PassObj constructor.
In this call to the constructor: `new PassObj(5,6);` arguments 5 and 6 are called "Actual parameters";
Here

``````PassObj(int p1, int p2)
{...}``````
p1 and p2 are called formal parameters.

What is the point of `PassObj(int p1, int p2)`:

Sign In or Register to comment.