Constructors
A new plant should get its name and height the moment it's created. That's the job of a constructor: code in the class that runs when an object is built with new, and gives the instance variables their first values.
public class Main {
public static void main(String[] args) {
System.out.println("Start");
Plant fern = new Plant("fern", 30);
Plant cactus = new Plant("cactus", 12);
System.out.println("End");
}
}public class Plant {
private String name;
private int height;
public Plant(String name, int height) {
this.name = name;
this.height = height;
System.out.println("Planted a " + this.name + ", " + this.height + " cm");
}
}Start
Planted a fern, 30 cm
Planted a cactus, 12 cm
End(Constructors don't usually print anything. This one does, so that you can see when it runs: once for each new.)
- A constructor is written like a method, but it has the class's name and no return type, not even
void:public Plant(String name, int height). - Its parameters work like a method's.
new Plant("fern", 30)gives"fern"tonameand 30 toheight, in that order. thismeans the object being built.this.nameis the object's instance variablename, whilenameon its own is the parameter. Sothis.name = name;copies the parameter's value into the object. A parameter with the same name as the instance variable it fills is the usual way to write a constructor; module 18 looks atthismore closely.- The parameters disappear when the constructor ends, but the values stored in the instance variables stay with the object for as long as it exists.
Not every instance variable needs a parameter. The Lamp in step 1 is built with only its place, and its constructor starts every lamp off with this.on = false;.
When the values don't fit
A class without any constructor gets the default constructor from step 2, which takes no values, so it's built with empty parentheses. Once Plant has a constructor of its own that takes a name and a height, Java no longer adds the default one, and every new Plant must give both values, just as a method call must fit the method's parameters:
public class Main {
public static void main(String[] args) {
Plant basil = new Plant();
}
}public class Plant {
private String name;
private int height;
public Plant(String name, int height) {
this.name = name;
this.height = height;
}
}Main.java:3: error: constructor Plant in class Plant cannot be applied to given types;
Plant basil = new Plant();
^
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 errorrequired lists the constructor's parameters, and found what the new gave. With the values the wrong way round, as in new Plant(30, "basil"), javac says incompatible types: int cannot be converted to String.