Classes and objects

Java · Essentials · 14 min

Java is built around objects; every real program models its domain as classes.

A class is a blueprint: it declares the data each object holds (fields) and the behaviour it offers (methods). An object is one instance created from that blueprint with new.

class Counter {
    int count;                 // field: each object has its own
    void increment() { count++; }
}
Counter c = new Counter();     // create an object
c.increment();

Methods without static are instance methods: they run on a particular object and can read and change its fields. Inside them, this refers to that object; you need it explicitly only to disambiguate, e.g. this.name = name.

static members belong to the class, shared by all instances. Use them for utilities (Math.max) and constants, not for per-object state.

A variable of a class type holds a reference, not the object itself. Two variables can refer to the same object, and passing an object to a method passes the reference. A reference that points to nothing is null; calling a method on it throws NullPointerException. Since Java 14 the error message names exactly which expression was null, which makes these easy to debug.

Fields get default values (0, false, null), unlike local variables which must be assigned before use.

Override toString() so objects print meaningfully: Java calls it automatically in string concatenation and println. Without it you get output like Counter@1b6d3586.

Objects you no longer reference are reclaimed automatically by the garbage collector — there is no delete in Java.

Example

public class Shop {
    static class Product {
        String name;
        double price;
        int stock;

        boolean sell(int qty) {
            if (qty > stock) return false;
            stock -= qty;
            return true;
        }

        @Override public String toString() { return name + " ($" + price + ", " + stock + " left)"; }
    }

    public static void main(String[] args) {
        Product p = new Product();
        p.name = "Mug"; p.price = 8.5; p.stock = 3;
        Product same = p;               // second reference to the same object
        same.sell(2);
        System.out.println(p);          // Mug ($8.5, 1 left)
        System.out.println(p.sell(5));  // false
    }
}

Remember

  • A class defines fields and methods; new creates an object
  • Variables hold references — several can point at one object
  • Override toString() for readable output

Watch out for

  • Calling an instance method on a reference that was never assigned an object, causing NullPointerException.

Check yourself

  1. Two variables `a` and `b` reference the same object, and you call `b.increment()`. What does `a.count` show?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.oracle.com/javase/tutorial/java/javaOO/classes.html