el_kraken
el_kraken

Reputation: 93

In Java, can the number of variables passed in value be less than the number of variables in the object's class?

This is an excerpt from Oracle's Java tutorial website. It doesn't show the actual .java files, but I'm guessing "Rectangle" is a class. But if you note, the parameters passed down (by value?) for rectOne and rectTwo are different. (one has the origin variable while two does not)

If the object has certain number of parameters, can the actual number of passed down values be less than that? I'm assuming it can't be more by default.

Also, I searched for answers but cannot find.

// Declare and create a point object and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

Upvotes: 0

Views: 153

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502206

An object doesn't have parameters - a method or a constructor does. In this case, basically there are two overloaded constructors. For example:

public Rectangle(Point origin, int width, int height)
{
    this.origin = origin;
    this.width = width;
    this.height = height;
}

public Rectangle(int width, int height)
{
    this(Point.ZERO, width, height);
}

The only time in which the number of argument expressions for a single overload can vary is with varargs:

public void foo(String... bar)
{
    ...
}

foo("x"); // Equivalent to foo(new String[] { "x" })
foo("x", "y"); // Equivalent to foo(new String[] { "x", "y" })
foo("x", "y", "z"); // Equivalent to foo(new String[] { "x", "y", "z" })

Upvotes: 12

Meera Anand
Meera Anand

Reputation: 348

Rectangle is a class and it has 2 constructors. One constructor takes in 3 parameters and the other takes 2.

While initializing objects you would have to make sure that you pass the required number of parameters as present in the constructors of the class.

Upvotes: 0

Juan Barahona
Juan Barahona

Reputation: 192

It's an exercise from the Classes topic. I read it too. You can create your own classes as the tutorials showed. Here you have 2 constructors for the class Rectangle1Class with different signatures. One accepts three parameters and the other only two. Try it and it will work. You have to create your class and methods to make it work. For example:

public Rectangle1Class(PointClass cOrigin, int cWidth, int cHeight){
    origin = cOrigin;
    width = cWidth;
    height = cHeight;
}

public Rectangle1Class(int cWidth, int cHeight){
    width = cWidth;
    height = cHeight;
}

Upvotes: 1

Related Questions