Classes and Objects

Basic Java
≈ 3 min read

A class defines a new type

Until now, you have mostly worked with ready-made types: numbers, strings, and arrays. But programs often need entities from their own domain: a user, an order, a car, a game character. You can describe your own types for such entities using classes.

A class is a description of an object type: which actions such objects can perform and what data can be associated with them. Declaring a class does not create an object yet. It only tells Java how the new type is structured.

class Robot {
    void greet() {
        System.out.println("Beep!");
    }
}

Here, a Robot type appears with the already familiar greet() method. You can now use this type just like other Java types: for example, you can declare variables of type Robot.

An object is a specific instance of a class

For a class to take part in the program's work, you create an object from it. An object is also called an instance of a class. An expression with new creates a new object, and a variable lets you access it.

class Robot {
    void greet() {
        System.out.println("Beep!");
    }
}

public class Main {
    public static void main(String[] args) {
        Robot robot = new Robot();
        robot.greet();
    }
}

It is convenient to read Robot robot = new Robot(); from right to left: create a Robot object and store a reference to it in the robot variable. Then the dot is used to call a method on that particular object.

A variable stores a reference to an object

An object and a variable are not the same thing. A variable of an object type stores a reference that leads to the object. That is why the same reference can be assigned to another variable. Such an assignment does not create a new object.

Robot first = new Robot();
Robot second = first;

second.greet();

After the second = first assignment, both variables refer to the very same object. This is different from a second new Robot() call: each separate execution of new creates a separate instance.

Assigning a reference does not copy the object. If two variables receive a reference to the same instance, both of them provide access to that exact object. This model becomes especially important when objects start storing their own data.

One class — many objects

A class is usually described once, while any number of objects of that class can exist while the program is running. That is the core idea: the class defines the common type and behavior, while each created instance represents a separate object of that type.

Robot first = new Robot();
Robot second = new Robot();

first.greet();
second.greet();

Here, first and second refer to different objects, because new Robot() was executed twice. When reading object-oriented code, it is useful to keep three things separate: the class declaration, the created instance, and the reference variable through which the program accesses it.