{"id":"class-design-this-call","slug":"constructor-calling-constructor","title":"One constructor calling another","text":"The two constructors of `CoffeeOrder` in step 3 repeat each other: both store a drink and a size. That's only two lines, but setting up an object often takes more. Say the café adds a rule: it only has small, medium and large cups, and any other size is made a medium. With every constructor setting up the object on its own, a rule like that has to be written into each of them, and so does every instance variable the class gets later.\n\nInstead, a constructor can hand the work to another constructor of the same class, with `this(...)`:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println(new CoffeeOrder(\"latte\", \"large\"));\n        System.out.println(new CoffeeOrder(\"tea\", \"huge\"));\n        System.out.println(new CoffeeOrder(\"mocha\"));\n        System.out.println(new CoffeeOrder());\n    }\n}\n// ==== CoffeeOrder.java ====\npublic class CoffeeOrder {\n    private String drink;\n    private String size;\n\n    public CoffeeOrder(String drink, String size) {\n        this.drink = drink;\n        if (size.equals(\"small\") || size.equals(\"large\")) {\n            this.size = size;\n        } else {\n            this.size = \"medium\";\n        }\n    }\n\n    public CoffeeOrder(String drink) {\n        this(drink, \"medium\");\n    }\n\n    public CoffeeOrder() {\n        this(\"filter coffee\");\n    }\n\n    public String toString() {\n        return this.size + \" \" + this.drink;\n    }\n}\n```\n\n```output\nlarge latte\nmedium tea\nmedium mocha\nmedium filter coffee\n```\n\n- `this(drink, \"medium\");` runs the constructor that takes two Strings, with the drink and the default size. That constructor sets up the object, and the one-parameter constructor has nothing else to do.\n- `this(\"filter coffee\");` runs the one-parameter constructor, which in turn runs the two-parameter one. However an order is made, it goes through the same code, so the size rule is written once.\n- Java picks the constructor for `this(...)` the same way as for `new`: by the values in the parentheses.\n\n`this(...)` and `this.size` look alike but are different things. `this.size` is the object's instance variable. `this` with parentheses right after it runs another constructor on the same object, the one being built. It doesn't make a new object. Writing `new CoffeeOrder(drink, \"medium\");` inside a constructor would build a second, separate order and throw it away, and the order being built would get no drink at all.\n\n### It must come first\n\n`this(...)` can only be used in a constructor, and it must be the constructor's first statement. Anything before it is an error:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        CoffeeOrder order = new CoffeeOrder(\"latte\");\n    }\n}\n// ==== CoffeeOrder.java ====\npublic class CoffeeOrder {\n    private String drink;\n    private String size;\n\n    public CoffeeOrder(String drink, String size) {\n        this.drink = drink;\n        this.size = size;\n    }\n\n    public CoffeeOrder(String drink) {\n        System.out.println(\"New order\");\n        this(drink, \"medium\");\n    }\n}\n```\n\n```javac\nCoffeeOrder.java:12: error: call to this must be first statement in constructor\n        this(drink, \"medium\");\n            ^\n1 error\n```\n\nAfter `this(...)`, a constructor may do more: its other lines run once the other constructor has finished.\n","task":"`Bouquet.java` has a constructor that takes a kind of flower and a number of stems. Add a second constructor, `Bouquet(String flower)`, for the florist's usual bouquet of 12 stems. Don't store the values in it: call the other constructor with `this(...)`. The check runs:\n\n```java\nBouquet usual = new Bouquet(\"tulips\");\nBouquet small = new Bouquet(\"roses\", 5);\nSystem.out.println(usual);\nSystem.out.println(small);\n```\n\nand expects:\n\n```\n12 tulips\n5 roses\n```\n","kind":"code","seed":"// ==== Bouquet.java ====\npublic class Bouquet {\n    private String flower;\n    private int stems;\n\n    public Bouquet(String flower, int stems) {\n        this.flower = flower;\n        this.stems = stems;\n        if (this.stems < 1) {\n            this.stems = 1;\n        }\n    }\n\n    // Write the second constructor here.\n\n    public String toString() {\n        return this.stems + \" \" + this.flower;\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Bouquet usual = new Bouquet(\"tulips\");\n        Bouquet small = new Bouquet(\"roses\", 5);\n        System.out.println(usual);\n        System.out.println(small);\n    }\n}\n","solution":"// ==== Bouquet.java ====\npublic class Bouquet {\n    private String flower;\n    private int stems;\n\n    public Bouquet(String flower, int stems) {\n        this.flower = flower;\n        this.stems = stems;\n        if (this.stems < 1) {\n            this.stems = 1;\n        }\n    }\n\n    public Bouquet(String flower) {\n        this(flower, 12);\n    }\n\n    public String toString() {\n        return this.stems + \" \" + this.flower;\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Bouquet usual = new Bouquet(\"tulips\");\n        Bouquet small = new Bouquet(\"roses\", 5);\n        System.out.println(usual);\n        System.out.println(small);\n    }\n}\n","hints":["The new constructor's header is `public Bouquet(String flower) {`.","Its only line runs the other constructor, with the flower and the default number of stems: `this(flower, 12);`."],"tests":[{"name":"Test 1","stdin":"","call":"Bouquet usual = new Bouquet(\"tulips\");\nBouquet small = new Bouquet(\"roses\", 5);\nSystem.out.println(usual);\nSystem.out.println(small);\n","expect":"12 tulips\n5 roses","hidden":false},{"name":"Test 2","stdin":"","call":"System.out.println(new Bouquet(\"daisies\"));\nSystem.out.println(new Bouquet(\"lilies\", 0));\n","expect":"12 daisies\n1 lilies","hidden":true},{"name":"Test 3","stdin":"","call":"Bouquet a = new Bouquet(\"sunflowers\", 3);\nBouquet b = new Bouquet(\"peonies\");\nSystem.out.println(b);\nSystem.out.println(a);\n","expect":"12 peonies\n3 sunflowers","hidden":true}],"require":[{"pattern":"\\bthis\\s*\\(","message":"Let the new constructor call the other one with `this(flower, 12);`."}],"forbid":[],"more":[{"task":"Here's the `Snowman` from step 3, with three constructors that each store both values. Rewrite the first two so that only `Snowman(int balls, String nose)` stores anything: `Snowman(int balls)` calls it with a carrot nose, and `Snowman()` calls one of the other constructors for 3 balls. The output stays the same:\n\n```\n3 balls, carrot nose\n4 balls, carrot nose\n2 balls, pine cone nose\n```\n","kind":"code","seed":"// ==== Snowman.java ====\npublic class Snowman {\n    private int balls;\n    private String nose;\n\n    public Snowman() {\n        this.balls = 3;\n        this.nose = \"carrot\";\n    }\n\n    public Snowman(int balls) {\n        this.balls = balls;\n        this.nose = \"carrot\";\n    }\n\n    public Snowman(int balls, String nose) {\n        this.balls = balls;\n        this.nose = nose;\n    }\n\n    public String toString() {\n        return this.balls + \" balls, \" + this.nose + \" nose\";\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println(new Snowman());\n        System.out.println(new Snowman(4));\n        System.out.println(new Snowman(2, \"pine cone\"));\n    }\n}\n","solution":"// ==== Snowman.java ====\npublic class Snowman {\n    private int balls;\n    private String nose;\n\n    public Snowman() {\n        this(3);\n    }\n\n    public Snowman(int balls) {\n        this(balls, \"carrot\");\n    }\n\n    public Snowman(int balls, String nose) {\n        this.balls = balls;\n        this.nose = nose;\n    }\n\n    public String toString() {\n        return this.balls + \" balls, \" + this.nose + \" nose\";\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println(new Snowman());\n        System.out.println(new Snowman(4));\n        System.out.println(new Snowman(2, \"pine cone\"));\n    }\n}\n","hints":["`Snowman(int balls)` becomes one line: `this(balls, \"carrot\");`.","`Snowman()` becomes one line too: `this(3);` runs `Snowman(int balls)`, which runs the two-parameter constructor. (`this(3, \"carrot\");` works as well.)"],"tests":[{"name":"Test 1","stdin":"","call":"System.out.println(new Snowman());\nSystem.out.println(new Snowman(4));\nSystem.out.println(new Snowman(2, \"pine cone\"));\n","expect":"3 balls, carrot nose\n4 balls, carrot nose\n2 balls, pine cone nose","hidden":false},{"name":"Test 2","stdin":"","call":"System.out.println(new Snowman(5, \"button\"));\nSystem.out.println(new Snowman(6));\n","expect":"5 balls, button nose\n6 balls, carrot nose","hidden":true},{"name":"Test 3","stdin":"","call":"Snowman a = new Snowman(2);\nSnowman b = new Snowman();\nSystem.out.println(b);\nSystem.out.println(a);\n","expect":"3 balls, carrot nose\n2 balls, carrot nose","hidden":true}],"require":[{"pattern":"\\bthis\\s*\\(","min":2,"message":"Let the two shorter constructors call another constructor with `this(...)`."},{"pattern":"\\bthis\\.balls\\s*=","max":1,"message":"Only `Snowman(int balls, String nose)` should store the balls: let the others call it with `this(...)`."},{"pattern":"\\bthis\\.nose\\s*=","max":1,"message":"Only `Snowman(int balls, String nose)` should store the nose: let the others call it with `this(...)`."}],"forbid":[]},{"task":"What does this program print? Each constructor of `Lantern` prints a line, so you can see when it runs. (Constructors don't usually print anything.)\n","kind":"predict","seed":"public class Main {\n    public static void main(String[] args) {\n        Lantern first = new Lantern();\n        Lantern second = new Lantern(\"glass\", 3);\n    }\n}\n// ==== Lantern.java ====\npublic class Lantern {\n    private String material;\n    private int candles;\n\n    public Lantern() {\n        this(\"paper\");\n        System.out.println(\"The usual lantern\");\n    }\n\n    public Lantern(String material) {\n        this(material, 1);\n        System.out.println(\"Made of \" + material);\n    }\n\n    public Lantern(String material, int candles) {\n        this.material = material;\n        this.candles = candles;\n        System.out.println(\"Candles: \" + candles);\n    }\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        Lantern first = new Lantern();\n        Lantern second = new Lantern(\"glass\", 3);\n    }\n}\n// ==== Lantern.java ====\npublic class Lantern {\n    private String material;\n    private int candles;\n\n    public Lantern() {\n        this(\"paper\");\n        System.out.println(\"The usual lantern\");\n    }\n\n    public Lantern(String material) {\n        this(material, 1);\n        System.out.println(\"Made of \" + material);\n    }\n\n    public Lantern(String material, int candles) {\n        this.material = material;\n        this.candles = candles;\n        System.out.println(\"Candles: \" + candles);\n    }\n}\n","hints":["`new Lantern()` starts with `this(\"paper\")`, which starts with `this(\"paper\", 1)`. The innermost constructor finishes first and prints first.","Each constructor prints its line after the constructor it called has finished. `new Lantern(\"glass\", 3)` runs only the two-parameter constructor."],"tests":[{"name":"Output","stdin":"","expect":"Candles: 1\nMade of paper\nThe usual lantern\nCandles: 3","hidden":false}],"require":[],"forbid":[],"lines":["Candles: 1","Made of paper","The usual lantern","Candles: 3"]}]}