Classes and Objects

OOP · lesson 1 of 43 · 3 min read

How a class becomes an object, and why a variable holds a reference rather than the object itself.

Open this lesson in the learning hub

Key points

  • A class is the blueprint. An object is one thing built from it. new builds one and hands you a reference.
  • Fields hold state, methods hold behaviour. Keeping the two together is the whole idea of object orientation.
  • Variables never hold objects, only references. a = b copies the arrow, not the thing it points at.
  • == asks "is this the same object?" It does not ask "do these look alike?" That question is equals.
  • Objects live on the heap. The garbage collector frees them once nothing references them, so there is no delete.

Example

public class Main {
    // A class is a blueprint. Every 'new' builds one object on the heap.
    static class Dog {
        String name;
        int age;

        void bark() {
            System.out.println(name + " says woof");
        }
    }

    public static void main(String[] args) {
        Dog rex = new Dog();
        rex.name = "Rex";
        rex.age = 3;
        rex.bark();

        Dog alias = rex;   // copies the reference, NOT the object
        alias.age = 4;
        System.out.println("rex.age  = " + rex.age);
        System.out.println("same?    = " + (rex == alias));

        Dog bella = new Dog();
        bella.name = "Bella";
        System.out.println("same?    = " + (rex == bella));
    }
}

A class is a blueprint; a variable holds a reference, never the object itself.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.