Hello,
I was wondering why do we need constructors with arguments?
Thank you

So that we can initialize our program's variables without knowing ahead of time what they should be initialized to. Consider the String class (that Java provides for you). If there wasn't a constructor String s = new String("This is what it'll say!"); then I couldn't make the String say that. As another example, consider two classes (I'm just making these up here)

public class AutomotiveFactory{

public static void main(String[] args){
Car customizedCar = new Car(true, true, false);
}

}

public class Car{
boolean hasABS = false;
boolean hasAirbags = false;
boolean foreignParts = false;

public Car(boolean hasABS, boolean hasAirbags, boolean foreignParts){
this.hasABS = hasABS;
this.hasAirbags = hasAirbags;
this.foreignParts = foreignParts;
}

}

Without these constructors, how would I create my customized car? I would have to call methods one by one to set the car's features to what I wanted, which is more code. And in the case of Java's String class, since it is immutable, you cannot even change the String once you create it so the constructor is not only helpful, but absolutely necessary.

... and a few more examples:
Open a window with a given title, text, and buttons.
Open a TCP/IP server on a given port.
Open a file, given the file name.
Start a randon number generator with a given seed.
...
in each case the things that are "given" are most conveniently passed as arguments to the constructor

> I was wondering why do we need constructors with arguments?

  • Creation of an object based on an existing one [though this can be done the `Cloneable' way, constructor based approach is also pretty flexible]
  • Creation of an object with known state [bind the ServerSocket to port XXX]
  • Prevent creation of objects with invalid initial state [by making the no-arg constructor as private. E.g. you wouldn't want a Policy object in your financial system to have a blank state; a Policy business object if created *always* has an initial state in the form of a policy number and other mandatory attributes. Ditto with Streams in Java and so on]
Comments
Full marks !!! Explains (concisely) everything.

S.o.S:

Isn't it true that if you define a constructor, Java does not automatically provide the default one? So by defining any constructor, there would be no default constructor, unless it was programmer defined. ?

Indeed, that's why I specifically mentioned a no-arg constructor[in case the class already has one] and not a default constructor. A default constructor is a no-arg constructor but the reverse doesn't make sense since if you explicitly define a no-arg constructor, there isn't anything *default* about it.

This article has been dead for over six months. Start a new discussion instead.