{"id":"classes-objects","slug":"objects-you-know","title":"Objects you already know","text":"You've been using **objects** since module 2. A Scanner is an object, every String is an object, and so is every ArrayList. An object holds some data, and it has methods, which you call with a dot after it: `scanner.nextLine()`, `word.length()`, `list.add(\"tea\")`.\n\nTwo objects of the same kind each have their own data:\n\n```java\nString city = \"Lima\";\nString river = \"Mississippi\";\nSystem.out.println(city.length());\nSystem.out.println(river.length());\n\nArrayList<String> groceries = new ArrayList<>();\nArrayList<String> chores = new ArrayList<>();\ngroceries.add(\"milk\");\ngroceries.add(\"eggs\");\nchores.add(\"dishes\");\nSystem.out.println(groceries.size());\nSystem.out.println(chores.size());\n```\n\n```output\n4\n11\n2\n1\n```\n\n`city.length()` and `river.length()` run the same method, but each answers for its own text. `groceries` and `chores` are two separate lists: adding to one doesn't touch the other.\n\n### Classes and new\n\nEvery object is made from a **class**. The class is the blueprint: it says what data each object holds and which methods it has. One class can make as many objects as you like, just as one blueprint can be used for a whole street of houses. Each house is built to the same plan, and painting one front door doesn't paint the others.\n\n- `ArrayList` is a class. `new ArrayList<>()` builds a new, empty list object from it.\n- `Scanner` is a class too, and `new Scanner(System.in)` builds a scanner that reads what the user types. The value in the parentheses is given to the new object as it's built.\n- `String` is a class. Strings are usually made by writing text in quotes, without `new`, but each one is still an object.\n\nThe type of a variable that holds an object is the name of its class: `Scanner scanner` is a variable that holds a Scanner.\n\n### A class in its own file\n\nJava comes with a large library of ready-made classes, and a program can also have classes of its own. Each one is written in a file of its own, named after the class: the class `Lamp` is in the file `Lamp.java`. Here's a program of two files. You don't need to read `Lamp.java` closely yet: the next steps show how a class like it is written, line by line.\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        Lamp desk = new Lamp(\"desk\");\n        Lamp porch = new Lamp(\"porch\");\n        desk.turnOn();\n        desk.printState();\n        porch.printState();\n    }\n}\n// ==== Lamp.java ====\npublic class Lamp {\n    private String place;\n    private boolean on;\n\n    public Lamp(String place) {\n        this.place = place;\n        this.on = false;\n    }\n\n    public void turnOn() {\n        this.on = true;\n    }\n\n    public void turnOff() {\n        this.on = false;\n    }\n\n    public void printState() {\n        if (this.on) {\n            System.out.println(\"The \" + this.place + \" lamp is on\");\n        } else {\n            System.out.println(\"The \" + this.place + \" lamp is off\");\n        }\n    }\n}\n```\n\n```output\nThe desk lamp is on\nThe porch lamp is off\n```\n\n- `new Lamp(\"desk\")` builds a new Lamp object and gives it the text `\"desk\"`. `Lamp desk` is a variable that holds a Lamp.\n- `desk.turnOn()` calls `turnOn` on the desk lamp only. The porch lamp is a separate object, so it's still off.\n- To use a class, you only need to know its methods and what they do, the same way you use an ArrayList without ever seeing its code.\n\nIn a challenge with several files, the editor shows a tab for each file, and **Check** compiles them all together.\n","task":"The program reads the name of a room. In `Main.java`, create a Lamp for that room, print its state, turn it on, and print its state again. Use the `Lamp` class in the other tab as it is. For the input `kitchen` the program prints:\n\n```\nThe kitchen lamp is off\nThe kitchen lamp is on\n```\n","kind":"code","seed":"// ==== Main.java ====\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String room = scanner.nextLine();\n\n    }\n}\n\n// ==== Lamp.java ====\npublic class Lamp {\n    private String place;\n    private boolean on;\n\n    public Lamp(String place) {\n        this.place = place;\n        this.on = false;\n    }\n\n    public void turnOn() {\n        this.on = true;\n    }\n\n    public void turnOff() {\n        this.on = false;\n    }\n\n    public void printState() {\n        if (this.on) {\n            System.out.println(\"The \" + this.place + \" lamp is on\");\n        } else {\n            System.out.println(\"The \" + this.place + \" lamp is off\");\n        }\n    }\n}\n","solution":"// ==== Main.java ====\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String room = scanner.nextLine();\n        Lamp lamp = new Lamp(room);\n        lamp.printState();\n        lamp.turnOn();\n        lamp.printState();\n    }\n}\n\n// ==== Lamp.java ====\npublic class Lamp {\n    private String place;\n    private boolean on;\n\n    public Lamp(String place) {\n        this.place = place;\n        this.on = false;\n    }\n\n    public void turnOn() {\n        this.on = true;\n    }\n\n    public void turnOff() {\n        this.on = false;\n    }\n\n    public void printState() {\n        if (this.on) {\n            System.out.println(\"The \" + this.place + \" lamp is on\");\n        } else {\n            System.out.println(\"The \" + this.place + \" lamp is off\");\n        }\n    }\n}\n","hints":["Create the lamp with the room's name: `Lamp lamp = new Lamp(room);`.","Then call the methods on it, in order: `lamp.printState();`, `lamp.turnOn();` and `lamp.printState();` again."],"tests":[{"name":"Test 1","stdin":"kitchen\n","expect":"The kitchen lamp is off\nThe kitchen lamp is on","hidden":false},{"name":"Test 2","stdin":"attic\n","expect":"The attic lamp is off\nThe attic lamp is on","hidden":true},{"name":"Test 3","stdin":"living room\n","expect":"The living room lamp is off\nThe living room lamp is on","hidden":true}],"require":[{"pattern":"\\bnew\\s+Lamp\\s*\\(","message":"Create the lamp with `new Lamp(room)`."},{"pattern":"\\.turnOn\\s*\\(\\s*\\)","message":"Turn the lamp on with its `turnOn()` method."},{"pattern":"\\.printState\\s*\\(\\s*\\)","min":2,"message":"Print the lamp's state with its `printState()` method, before and after turning it on."}],"forbid":[],"more":[{"task":"What does this program print? Keep track of each lamp separately.\n","kind":"predict","seed":"public class Main {\n    public static void main(String[] args) {\n        Lamp hall = new Lamp(\"hall\");\n        Lamp garage = new Lamp(\"garage\");\n        hall.turnOn();\n        garage.turnOn();\n        hall.turnOff();\n        hall.printState();\n        garage.printState();\n        Lamp spare = new Lamp(\"hall\");\n        spare.turnOn();\n        hall.printState();\n    }\n}\n// ==== Lamp.java ====\npublic class Lamp {\n    private String place;\n    private boolean on;\n\n    public Lamp(String place) {\n        this.place = place;\n        this.on = false;\n    }\n\n    public void turnOn() {\n        this.on = true;\n    }\n\n    public void turnOff() {\n        this.on = false;\n    }\n\n    public void printState() {\n        if (this.on) {\n            System.out.println(\"The \" + this.place + \" lamp is on\");\n        } else {\n            System.out.println(\"The \" + this.place + \" lamp is off\");\n        }\n    }\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        Lamp hall = new Lamp(\"hall\");\n        Lamp garage = new Lamp(\"garage\");\n        hall.turnOn();\n        garage.turnOn();\n        hall.turnOff();\n        hall.printState();\n        garage.printState();\n        Lamp spare = new Lamp(\"hall\");\n        spare.turnOn();\n        hall.printState();\n    }\n}\n// ==== Lamp.java ====\npublic class Lamp {\n    private String place;\n    private boolean on;\n\n    public Lamp(String place) {\n        this.place = place;\n        this.on = false;\n    }\n\n    public void turnOn() {\n        this.on = true;\n    }\n\n    public void turnOff() {\n        this.on = false;\n    }\n\n    public void printState() {\n        if (this.on) {\n            System.out.println(\"The \" + this.place + \" lamp is on\");\n        } else {\n            System.out.println(\"The \" + this.place + \" lamp is off\");\n        }\n    }\n}\n","hints":["`hall` and `garage` are two separate lamps. Both are turned on, and then only the hall lamp is turned off again.","`spare` is a third lamp. Its place is also `hall`, but it's a different object, so turning it on doesn't change the lamp in `hall`."],"tests":[{"name":"Output","stdin":"","expect":"The hall lamp is off\nThe garage lamp is on\nThe hall lamp is off","hidden":false}],"require":[],"forbid":[],"lines":["The hall lamp is off","The garage lamp is on","The hall lamp is off"]},{"task":"`Poll.java` holds a class for a quick vote. Write `Main`: the first line of input is the question, and every line after it is a vote, `y` or `n`, until the line `end`. Create a Poll for the question, give it each vote with `voteYes()` or `voteNo()`, and at the end call `printResult()`. The poll does the counting, so `Main` needs no counters of its own. For the input `Pizza on Friday?`, `y`, `n`, `y` and `end`, one per line, the program prints:\n\n```\nPizza on Friday?\nYes 2, no 1\n```\n","kind":"code","seed":"// ==== Main.java ====\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String question = scanner.nextLine();\n\n    }\n}\n\n// ==== Poll.java ====\npublic class Poll {\n    private String question;\n    private int yes;\n    private int no;\n\n    public Poll(String question) {\n        this.question = question;\n        this.yes = 0;\n        this.no = 0;\n    }\n\n    public void voteYes() {\n        this.yes = this.yes + 1;\n    }\n\n    public void voteNo() {\n        this.no = this.no + 1;\n    }\n\n    public void printResult() {\n        System.out.println(this.question);\n        System.out.println(\"Yes \" + this.yes + \", no \" + this.no);\n    }\n}\n","solution":"// ==== Main.java ====\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String question = scanner.nextLine();\n        Poll poll = new Poll(question);\n        while (true) {\n            String vote = scanner.nextLine();\n            if (vote.equals(\"end\")) {\n                break;\n            }\n            if (vote.equals(\"y\")) {\n                poll.voteYes();\n            } else if (vote.equals(\"n\")) {\n                poll.voteNo();\n            }\n        }\n        poll.printResult();\n    }\n}\n\n// ==== Poll.java ====\npublic class Poll {\n    private String question;\n    private int yes;\n    private int no;\n\n    public Poll(String question) {\n        this.question = question;\n        this.yes = 0;\n        this.no = 0;\n    }\n\n    public void voteYes() {\n        this.yes = this.yes + 1;\n    }\n\n    public void voteNo() {\n        this.no = this.no + 1;\n    }\n\n    public void printResult() {\n        System.out.println(this.question);\n        System.out.println(\"Yes \" + this.yes + \", no \" + this.no);\n    }\n}\n","hints":["Create the poll before the loop, so the same poll gets every vote: `Poll poll = new Poll(question);`.","In the loop, read a line and `break` at `end`. For `y` call `poll.voteYes();`, for `n` call `poll.voteNo();`. After the loop, `poll.printResult();`."],"tests":[{"name":"Test 1","stdin":"Pizza on Friday?\ny\nn\ny\nend\n","expect":"Pizza on Friday?\nYes 2, no 1","hidden":false},{"name":"Test 2","stdin":"Picnic in the rain?\nn\nn\nn\nend\n","expect":"Picnic in the rain?\nYes 0, no 3","hidden":true},{"name":"Test 3","stdin":"Any questions?\nend\n","expect":"Any questions?\nYes 0, no 0","hidden":true},{"name":"Test 4","stdin":"Longer breaks?\ny\ny\nn\ny\ny\nend\n","expect":"Longer breaks?\nYes 4, no 1","hidden":true}],"require":[{"pattern":"\\bnew\\s+Poll\\s*\\(","message":"Create the poll with `new Poll(question)`."},{"pattern":"\\.voteYes\\s*\\(\\s*\\)","message":"Give the poll each yes vote with `voteYes()`."},{"pattern":"\\.voteNo\\s*\\(\\s*\\)","message":"Give the poll each no vote with `voteNo()`."},{"pattern":"\\.printResult\\s*\\(\\s*\\)","message":"Print the result with the poll's `printResult()` method."}],"forbid":[]}]}