{"id":"classes-constructor","slug":"constructors","title":"Constructors","text":"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.\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println(\"Start\");\n        Plant fern = new Plant(\"fern\", 30);\n        Plant cactus = new Plant(\"cactus\", 12);\n        System.out.println(\"End\");\n    }\n}\n// ==== Plant.java ====\npublic class Plant {\n    private String name;\n    private int height;\n\n    public Plant(String name, int height) {\n        this.name = name;\n        this.height = height;\n        System.out.println(\"Planted a \" + this.name + \", \" + this.height + \" cm\");\n    }\n}\n```\n\n```output\nStart\nPlanted a fern, 30 cm\nPlanted a cactus, 12 cm\nEnd\n```\n\n(Constructors don't usually print anything. This one does, so that you can see when it runs: once for each `new`.)\n\n- 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)`.\n- Its parameters work like a method's. `new Plant(\"fern\", 30)` gives `\"fern\"` to `name` and 30 to `height`, in that order.\n- `this` means the object being built. `this.name` is the object's instance variable `name`, while `name` on its own is the parameter. So `this.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 at `this` more closely.\n- 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.\n\nNot 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;`.\n\n### When the values don't fit\n\nA 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:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        Plant basil = new Plant();\n    }\n}\n// ==== Plant.java ====\npublic class Plant {\n    private String name;\n    private int height;\n\n    public Plant(String name, int height) {\n        this.name = name;\n        this.height = height;\n    }\n}\n```\n\n```javac\nMain.java:3: error: constructor Plant in class Plant cannot be applied to given types;\n        Plant basil = new Plant();\n                      ^\n  required: String,int\n  found:    no arguments\n  reason: actual and formal argument lists differ in length\n1 error\n```\n\n`required` 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`.\n","task":"`Parcel.java` has its instance variables and a method that prints them. Write the constructor, so that `new Parcel(\"Amir\", 1200)` makes a parcel for Amir that weighs 1200 grams. The check runs:\n\n```java\nParcel parcel = new Parcel(\"Amir\", 1200);\nparcel.printInfo();\n```\n\nand expects:\n\n```\nParcel for Amir, 1200 g\n```\n","kind":"code","seed":"// ==== Parcel.java ====\npublic class Parcel {\n    private String recipient;\n    private int grams;\n\n    // Write the constructor here.\n\n    public void printInfo() {\n        System.out.println(\"Parcel for \" + this.recipient + \", \" + this.grams + \" g\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Parcel parcel = new Parcel(\"Amir\", 1200);\n        parcel.printInfo();\n    }\n}\n","solution":"// ==== Parcel.java ====\npublic class Parcel {\n    private String recipient;\n    private int grams;\n\n    public Parcel(String recipient, int grams) {\n        this.recipient = recipient;\n        this.grams = grams;\n    }\n\n    public void printInfo() {\n        System.out.println(\"Parcel for \" + this.recipient + \", \" + this.grams + \" g\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Parcel parcel = new Parcel(\"Amir\", 1200);\n        parcel.printInfo();\n    }\n}\n","hints":["The constructor has the class's name and no `void`: `public Parcel(String recipient, int grams) {`.","Inside it, store each parameter in its instance variable: `this.recipient = recipient;` and `this.grams = grams;`."],"tests":[{"name":"Test 1","stdin":"","call":"Parcel parcel = new Parcel(\"Amir\", 1200);\nparcel.printInfo();\n","expect":"Parcel for Amir, 1200 g","hidden":false},{"name":"Test 2","stdin":"","call":"Parcel parcel = new Parcel(\"Sofia\", 350);\nparcel.printInfo();\n","expect":"Parcel for Sofia, 350 g","hidden":true},{"name":"Test 3","stdin":"","call":"Parcel light = new Parcel(\"Ben\", 90);\nParcel heavy = new Parcel(\"Kai\", 5000);\nheavy.printInfo();\nlight.printInfo();\n","expect":"Parcel for Kai, 5000 g\nParcel for Ben, 90 g","hidden":true}],"require":[],"forbid":[],"more":[{"task":"A new water bottle comes full. `WaterBottle.java` has two instance variables, `capacity` and `milliliters` (how much water is in it), and a method `printInfo()`. Write the constructor `WaterBottle(int capacity)`: it stores the capacity and fills the bottle, so `milliliters` starts at the same value. The check runs:\n\n```java\nWaterBottle bottle = new WaterBottle(750);\nbottle.printInfo();\n```\n\nand expects:\n\n```\n750/750 ml\n```\n","kind":"code","seed":"// ==== WaterBottle.java ====\npublic class WaterBottle {\n    private int capacity;\n    private int milliliters;\n\n    // Write the constructor here.\n\n    public void printInfo() {\n        System.out.println(this.milliliters + \"/\" + this.capacity + \" ml\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        WaterBottle bottle = new WaterBottle(750);\n        bottle.printInfo();\n    }\n}\n","solution":"// ==== WaterBottle.java ====\npublic class WaterBottle {\n    private int capacity;\n    private int milliliters;\n\n    public WaterBottle(int capacity) {\n        this.capacity = capacity;\n        this.milliliters = capacity;\n    }\n\n    public void printInfo() {\n        System.out.println(this.milliliters + \"/\" + this.capacity + \" ml\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        WaterBottle bottle = new WaterBottle(750);\n        bottle.printInfo();\n    }\n}\n","hints":["The constructor has one parameter: `public WaterBottle(int capacity) {`.","Store the capacity with `this.capacity = capacity;`. The bottle starts full, so `this.milliliters = capacity;` too."],"tests":[{"name":"Test 1","stdin":"","call":"WaterBottle bottle = new WaterBottle(750);\nbottle.printInfo();\n","expect":"750/750 ml","hidden":false},{"name":"Test 2","stdin":"","call":"WaterBottle bottle = new WaterBottle(500);\nbottle.printInfo();\n","expect":"500/500 ml","hidden":true},{"name":"Test 3","stdin":"","call":"WaterBottle big = new WaterBottle(1000);\nWaterBottle small = new WaterBottle(330);\nsmall.printInfo();\nbig.printInfo();\n","expect":"330/330 ml\n1000/1000 ml","hidden":true}],"require":[],"forbid":[]},{"task":"This time, write the instance variables and the constructor yourself. A `Concert` has a band and a city (both Strings) and a ticket price in euros (an int), in instance variables called `band`, `city` and `price`. The constructor takes them in that order. The method `printPoster()` is already there. The check runs:\n\n```java\nConcert show = new Concert(\"The Owls\", \"Lisbon\", 25);\nshow.printPoster();\n```\n\nand expects:\n\n```\nThe Owls live in Lisbon!\nTickets 25 euros\n```\n","kind":"code","seed":"// ==== Concert.java ====\npublic class Concert {\n    // Write the instance variables and the constructor here.\n\n    public void printPoster() {\n        System.out.println(this.band + \" live in \" + this.city + \"!\");\n        System.out.println(\"Tickets \" + this.price + \" euros\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Concert show = new Concert(\"The Owls\", \"Lisbon\", 25);\n        show.printPoster();\n    }\n}\n","solution":"// ==== Concert.java ====\npublic class Concert {\n    private String band;\n    private String city;\n    private int price;\n\n    public Concert(String band, String city, int price) {\n        this.band = band;\n        this.city = city;\n        this.price = price;\n    }\n\n    public void printPoster() {\n        System.out.println(this.band + \" live in \" + this.city + \"!\");\n        System.out.println(\"Tickets \" + this.price + \" euros\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Concert show = new Concert(\"The Owls\", \"Lisbon\", 25);\n        show.printPoster();\n    }\n}\n","hints":["Three private instance variables at the top: `private String band;`, `private String city;` and `private int price;`.","The parameters come in the same order as in `new Concert(\"The Owls\", \"Lisbon\", 25)`: `public Concert(String band, String city, int price)`. Store each one with `this.`, as in `this.band = band;`."],"tests":[{"name":"Test 1","stdin":"","call":"Concert show = new Concert(\"The Owls\", \"Lisbon\", 25);\nshow.printPoster();\n","expect":"The Owls live in Lisbon!\nTickets 25 euros","hidden":false},{"name":"Test 2","stdin":"","call":"Concert show = new Concert(\"Moss Garden\", \"Tallinn\", 18);\nshow.printPoster();\n","expect":"Moss Garden live in Tallinn!\nTickets 18 euros","hidden":true},{"name":"Test 3","stdin":"","call":"Concert early = new Concert(\"Paper Boats\", \"Lyon\", 12);\nConcert late = new Concert(\"Night Owls\", \"Porto\", 30);\nlate.printPoster();\nearly.printPoster();\n","expect":"Night Owls live in Porto!\nTickets 30 euros\nPaper Boats live in Lyon!\nTickets 12 euros","hidden":true}],"require":[{"pattern":"\\bprivate\\s+(String|int)\\s+(band|city|price)\\s*[;=]","min":3,"message":"Declare the three instance variables as private: `private String band;`, `private String city;` and `private int price;`."}],"forbid":[]}]}