Objects & Classes
- Distinguish a class (the blueprint) from an object (an instance built from it)
- Create an object with the `new` keyword and a constructor
- Call a method on an object using dot notation to read its state
Classes are blueprints, objects are the buildings
A class is a blueprint that describes what a kind of thing knows (its data) and what it can do (its methods). An object is one concrete thing built from that blueprint. The String class, for example, is the blueprint; the specific text "robot" you store is an object — an instance of String. One class can produce many independent objects, each holding its own data.
Building an object with new
To build a new object you call a constructor with the new keyword: Rectangle r = new Rectangle(3, 4). Java sets aside memory for the object, runs the constructor to initialize it, and stores a reference to it in the variable r. The values in parentheses are arguments passed to the constructor. Some classes, like String, also let you create objects from a literal ("robot") without writing new yourself.
Talking to an object with dot notation
Once you hold a reference, you ask the object to do something with dot notation: object.method(arguments). The expression r.getArea() sends the getArea message to the object r, which runs that method and hands back a result. Reading an object’s data through a method like this is the everyday way objects are used in Java.
A Rectangle class has the constructor Rectangle(int width, int height) and a method getArea() that returns width * height. What does this code print? Rectangle r = new Rectangle(3, 4); then System.out.println(r.getArea());
- 1.The line
new Rectangle(3, 4)builds a Rectangle object with width3and height4, and stores a reference to it inr. - 2.The call
r.getArea()runsgetAreaon that object, computingwidth * height=3 * 4. - 3.
3 * 4evaluates to12, which is returned and passed toSystem.out.println.
12 — the area of a 3-by-4 rectangle.What does this code print? `String word = "robot";` then `System.out.println(word.length());`
A class name is a type (like Rectangle); an object is a specific value of that type built at runtime. Reading new Rectangle(3, 4) as "make me one Rectangle" keeps the blueprint-vs-building distinction clear.
A `Rectangle` has constructor `Rectangle(int width, int height)` and method `getArea()` returning `width * height`. What does this print? `Rectangle box = new Rectangle(5, 2);` then `System.out.println(box.getArea());`
On the exam, new always appears with a class that has a matching constructor. If the arguments do not match any constructor’s parameter list, the code fails to compile — check the number and types of arguments carefully.
Answer the 2 checkpoints as you read.
Sign in to save your progress