← Back to course

Objects & Classes

You’ll be able to

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.

Constructing and using an object
ClassName ref = new ClassName(args); ref.method(args);
`new` builds the object and returns a reference; dot notation then sends messages to it.
Worked example

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. 1.The line new Rectangle(3, 4) builds a Rectangle object with width 3 and height 4, and stores a reference to it in r.
  2. 2.The call r.getArea() runs getArea on that object, computing width * height = 3 * 4.
  3. 3.3 * 4 evaluates to 12, which is returned and passed to System.out.println.
Answer: It prints 12 — the area of a 3-by-4 rectangle.
Checkpoint

What does this code print? `String word = "robot";` then `System.out.println(word.length());`

Tip

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.

Checkpoint

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

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