Arguments
If you declare a constructor which takes arguments, you can use those arguments to give initial values to fields.1
You need to pass the arguments in the ()
in the new
expression, just like any other method invocation.
class Muppet {
String name;
Muppet(String name) {
this.name = name;
}
}
void main() {
Muppet gonzo = new Muppet("Gonzo");
// "Gonzo"
System.out.println(gonzo.name);
}
When you declare a constructor that takes arguments, the default constructor will no longer be available.
class Muppet {
String name;
Muppet(String name) {
this.name = name;
}
}
void main() {
// Need to provide a name now
Muppet gonzo = new Muppet();
}
1
Using this.
for disambiguation comes in handy here, since often the names of arguments
will be the same as the fields you want to populate with them.