{"id":"classes-creating","slug":"writing-a-class","title":"Writing a class","text":"Now you write classes of your own. The example in this module is a class for the plants in a garden, where every plant has a name and a height in centimeters.\n\n### The class and its file\n\nA class starts with `public class` and its name, and everything in it goes between its braces:\n\n```java\npublic class Plant {\n\n}\n```\n\n- A `public class Plant` must be in a file called `Plant.java`: the same name, capitals and all, plus `.java`. That's why `Main` has always been in `Main.java`.\n- Class names start with a capital letter, and so does each new word in them: `Plant`, `GardenBed`, `ArrayList`. Variables and methods start with a small letter.\n- The files of a program go side by side: in the editor as tabs, on your own computer in the same folder.\n- A class without `public` in front may share a file with another class. The practice drills show their small classes that way, after `Main` in the same file, but in the lessons every class has a file of its own.\n\n### Instance variables\n\nThe data that every object carries is declared at the top of the class, inside its braces but outside any method:\n\n```java\npublic class Plant {\n    private String name;\n    private int height;\n}\n```\n\nThese are **instance variables** (also called fields). An *instance* is an object made from a class, and each instance gets its own copy of every instance variable: one plant can be a 30 cm fern while another is a 12 cm cactus. An instance variable lives as long as its object does, while a method's own variables disappear when the method ends.\n\nEverything inside a class is indented one level (4 spaces), just as the lines of a method are indented inside the method.\n\n### private\n\n`private` means that only the code inside the `Plant` class can use the variable. Code in `Main` can't read it or change it:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        Plant fern = new Plant();\n        fern.height = 30;\n    }\n}\n// ==== Plant.java ====\npublic class Plant {\n    private String name;\n    private int height;\n}\n```\n\n```javac\nMain.java:4: error: height has private access in Plant\n        fern.height = 30;\n            ^\n1 error\n```\n\nWhy lock the data away? Because then the class decides what happens to it. When every change to `height` has to go through the class's own methods, the class can make sure that no plant ever gets a height of -20. Code outside the class uses a Plant through its methods, the way you use an ArrayList through `add` and `get` without touching its insides. Hiding the data like this is called **encapsulation**, and in this course instance variables are always `private`.\n\n### A class that does nothing yet\n\nThe class above already works as a blueprint: `Plant fern = new Plant();` builds a Plant object. When a class has no constructor of its own (that's the next step), Java gives it an empty one, called the **default constructor**, and that's what the empty parentheses call. The instance variables then start at default values: 0 for numbers, `false` for a boolean, and `null` for a String or any other object (`null` means \"no object at all\"). But this plant can't do anything yet: it has no methods, and nothing outside it can set its name or height. The next steps give it a constructor and methods.\n","task":"`Suitcase.java` already has a constructor and a method, and they use two instance variables: `owner`, a String, and `kilos`, an int. But nobody declared them, so the program doesn't compile. Declare them at the top of the class, as private instance variables. (Constructors and methods are the next steps: here you only add the variables.) The check runs:\n\n```java\nSuitcase bag = new Suitcase(\"Mei\", 18);\nbag.printLabel();\n```\n\nand expects:\n\n```\nOwner: Mei, 18 kg\n```\n","kind":"code","seed":"// ==== Suitcase.java ====\npublic class Suitcase {\n    // Declare the instance variables here.\n\n    public Suitcase(String owner, int kilos) {\n        this.owner = owner;\n        this.kilos = kilos;\n    }\n\n    public void printLabel() {\n        System.out.println(\"Owner: \" + this.owner + \", \" + this.kilos + \" kg\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Suitcase bag = new Suitcase(\"Mei\", 18);\n        bag.printLabel();\n    }\n}\n","solution":"// ==== Suitcase.java ====\npublic class Suitcase {\n    private String owner;\n    private int kilos;\n\n    public Suitcase(String owner, int kilos) {\n        this.owner = owner;\n        this.kilos = kilos;\n    }\n\n    public void printLabel() {\n        System.out.println(\"Owner: \" + this.owner + \", \" + this.kilos + \" kg\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Suitcase bag = new Suitcase(\"Mei\", 18);\n        bag.printLabel();\n    }\n}\n","hints":["The constructor stores values in `this.owner` and `this.kilos`, so the class needs instance variables with exactly those names.","At the top of the class, where the comment is, one line each, with `private` in front: `private String owner;` and `private int kilos;`."],"tests":[{"name":"Test 1","stdin":"","call":"Suitcase bag = new Suitcase(\"Mei\", 18);\nbag.printLabel();\n","expect":"Owner: Mei, 18 kg","hidden":false},{"name":"Test 2","stdin":"","call":"Suitcase bag = new Suitcase(\"Tomasz\", 23);\nbag.printLabel();\n","expect":"Owner: Tomasz, 23 kg","hidden":true},{"name":"Test 3","stdin":"","call":"Suitcase small = new Suitcase(\"Ana\", 7);\nSuitcase big = new Suitcase(\"Jon\", 31);\nbig.printLabel();\nsmall.printLabel();\n","expect":"Owner: Jon, 31 kg\nOwner: Ana, 7 kg","hidden":true}],"require":[{"pattern":"\\bprivate\\s+String\\s+owner\\s*[;=]","message":"Declare `owner` as a private String: `private String owner;`."},{"pattern":"\\bprivate\\s+int\\s+kilos\\s*[;=]","message":"Declare `kilos` as a private int: `private int kilos;`."}],"forbid":[],"more":[{"task":"In `Kayak.java`, the instance variables have no `private`, so code outside the class can change them, and a line in `Main.java` gives the kayak -3 seats. Make both variables private. javac then stops at that line in `Main.java` (`seats has private access in Kayak`), because only the Kayak class may change its seats now: delete the line. The program then prints:\n\n```\nSea Otter, 2 seats\n```\n","kind":"code","seed":"// ==== Kayak.java ====\npublic class Kayak {\n    String model;\n    int seats;\n\n    public Kayak(String model, int seats) {\n        this.model = model;\n        this.seats = seats;\n    }\n\n    public void printInfo() {\n        System.out.println(this.model + \", \" + this.seats + \" seats\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Kayak kayak = new Kayak(\"Sea Otter\", 2);\n        kayak.seats = -3;\n        kayak.printInfo();\n    }\n}\n","solution":"// ==== Kayak.java ====\npublic class Kayak {\n    private String model;\n    private int seats;\n\n    public Kayak(String model, int seats) {\n        this.model = model;\n        this.seats = seats;\n    }\n\n    public void printInfo() {\n        System.out.println(this.model + \", \" + this.seats + \" seats\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Kayak kayak = new Kayak(\"Sea Otter\", 2);\n        kayak.printInfo();\n    }\n}\n","hints":["Put `private` in front of both instance variables in `Kayak.java`: `private String model;` and `private int seats;`.","Then **Check** shows the error in `Main.java`, at `kayak.seats = -3;`. Delete that whole line: the kayak keeps the 2 seats its constructor gave it."],"tests":[{"name":"The program","stdin":"","expect":"Sea Otter, 2 seats","hidden":false},{"name":"Test 2","stdin":"","call":"Kayak kayak = new Kayak(\"River Fox\", 1);\nkayak.printInfo();\n","expect":"River Fox, 1 seats","hidden":true}],"require":[{"pattern":"\\bprivate\\s+String\\s+model\\s*[;=]","message":"Make `model` private: `private String model;`."},{"pattern":"\\bprivate\\s+int\\s+seats\\s*[;=]","message":"Make `seats` private: `private int seats;`."}],"forbid":[]},{"task":"`Thermostat.java` works, but its indentation is a mess. Re-indent it: everything inside the class one level in (4 spaces), and the lines inside the constructor and the method one level more. In this challenge, **Check** also checks the indentation. The program prints:\n\n```\nBedroom: 19 degrees\n```\n","kind":"code","seed":"// ==== Thermostat.java ====\npublic class Thermostat {\nprivate String room;\n      private int degrees;\n\n  public Thermostat(String room, int degrees) {\n  this.room = room;\n          this.degrees = degrees;\n      }\n\npublic void printSetting() {\nSystem.out.println(this.room + \": \" + this.degrees + \" degrees\");\n    }\n    }\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Thermostat bedroom = new Thermostat(\"Bedroom\", 19);\n        bedroom.printSetting();\n    }\n}\n","solution":"// ==== Thermostat.java ====\npublic class Thermostat {\n    private String room;\n    private int degrees;\n\n    public Thermostat(String room, int degrees) {\n        this.room = room;\n        this.degrees = degrees;\n    }\n\n    public void printSetting() {\n        System.out.println(this.room + \": \" + this.degrees + \" degrees\");\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Thermostat bedroom = new Thermostat(\"Bedroom\", 19);\n        bedroom.printSetting();\n    }\n}\n","hints":["The two variables and the two headers (`public Thermostat(...)` and `public void printSetting()`) are one level in: 4 spaces. The lines inside them are two levels in: 8 spaces.","Each closing `}` lines up with the start of the line that opened its block. The class's last `}` has no spaces before it."],"tests":[{"name":"The program","stdin":"","expect":"Bedroom: 19 degrees","hidden":false},{"name":"Test 2","stdin":"","call":"Thermostat office = new Thermostat(\"Office\", 21);\noffice.printSetting();\n","expect":"Office: 21 degrees","hidden":true}],"require":[],"forbid":[],"style":"indent"}]}