Skip to content
LumenaryAcademy
Foundations 55 min

Methods, classes and objects

Naming behaviour with methods, bundling state and behaviour into classes, and what a variable that "holds an object" really holds.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

From a script to a system

The programs so far have been one main method doing everything in order. That works for twenty lines. It stops working at two hundred, and a real Java service has hundreds of thousands. Two tools let a program grow without collapsing under its own weight.

A method gives a name to a piece of behaviour. Once isLeap(year) exists, nobody reading the code needs to remember the rule about centuries; the name says what happens, and the body is written and tested once.

A class goes further: it bundles data with the methods that are allowed to change it. A rainwater tank has a capacity and a current level, and the level must never be negative or above the capacity. If any line anywhere in a program can set the level, then every line is a suspect when the number goes wrong. If only the tank's own methods can change it, and each of them keeps the rule, then the rule holds everywhere, always. That idea, called encapsulation, is the heart of object-oriented design, and Java was built around it.

This lesson covers methods, then classes and the objects made from them, then the one fact about Java's memory model that every professional must have straight: what a variable of a class type actually holds.

IntuitionH

Blueprints, objects and labels

A class is a description: what data each object of this kind holds (its fields) and what it can do (its methods). An object is one concrete thing built from that description, with its own values for the fields. One Tank class can describe the tank on a school roof and the tank behind a clinic; they are two objects, each with its own level.

Objects live in a region of memory called the heap. A variable never contains an object; it contains a reference to one, which you can think of as the object's address.

Analogy, not a formal construction

A reference is like a luggage tag with a locker number on it. Copying the tag (Tank b = a;) does not copy the suitcase; now two tags point to the same locker, and whoever opens it with either tag sees the same contents. A tag can also be blank (null), and trying to open the locker of a blank tag is an error.

Primitive variables (int, double, boolean...) are different: they hold the value itself. Copying an int copies the number.

DefinitionsH

Definitions

Definition— Method signature and overloading

A method's signature is its name plus its parameter types. A class may have several methods with the same name and different parameter lists; this is overloading, and the compiler picks the best match from the argument types at compile time. The return type is not part of the signature.

Definition— Static and instance members

A static field or method belongs to the class as a whole: there is one copy, used as ClassName.member. An instance field or method belongs to each object: every object has its own copy of instance fields, and instance methods run "on" an object, which they can refer to as this.

Definition— Constructor

A special method with the class's name and no return type, run by new to initialise a fresh object. A class may have several constructors; one can delegate to another with this(...). If you write none, Java supplies an empty one.

Definition— Access modifiers

private (visible only inside the class), no modifier (visible inside the same package, "package-private"), protected (package plus subclasses) and public (visible everywhere). Fields are almost always private.

Definition— Invariant

A condition about an object's fields that is true after the constructor finishes and stays true after every public method call, such as "0 ≤ level ≤ capacity". Encapsulation exists to make invariants enforceable.

Worked examplesH

Methods: parameters, overloading, varargs

java
import java.util.Arrays;

public class Main {
    // Overloading: same name, different parameter lists
    static int largest(int a, int b) {
        return a >= b ? a : b;
    }

    static double largest(double a, double b) {
        return a >= b ? a : b;
    }

    // Varargs: any number of ints, received as an array
    static int sum(int... values) {
        int total = 0;
        for (int v : values) {
            total += v;
        }
        return total;
    }

    // Java passes every argument by value: a copy of the primitive, or a copy of the reference
    static void tryToChange(int number, int[] numbers) {
        number = 99;          // changes the local copy only
        numbers[0] = 99;      // changes the array both variables refer to
        numbers = new int[] {-1, -1, -1};   // re-points the local copy only
    }

    public static void main(String[] args) {
        System.out.println(largest(3, 8));
        System.out.println(largest(2.5, 1.5));
        System.out.println(sum());
        System.out.println(sum(4, 5, 6));

        int n = 1;
        int[] arr = {1, 2, 3};
        tryToChange(n, arr);
        System.out.println(n + " " + Arrays.toString(arr));
    }
}
text
8
2.5
0
15
1 [99, 2, 3]

A method declaration reads: modifiers (static), return type (int, or void for none), name, and parameters with their types. return ends the method and hands back a value; the compiler checks that every path through a non-void method returns one.

The two largest methods are overloads. largest(3, 8) picks the int version and largest(2.5, 1.5) the double one. Overloading is resolved entirely at compile time, from the static types of the arguments, and the rules for close calls are intricate (widening a primitive is preferred to boxing it, which is preferred to varargs). Keep overloads few and obviously different.

int... values declares varargs: callers pass any number of ints, and the method receives them as an array, possibly empty. String.format and List.of are varargs methods you already know.

The last line is the important one. Java always passes arguments by value. For an int, the value is the number, so tryToChange gets its own copy of 1 and changing it changes nothing outside. For an array (or any object), the value is the reference. The method gets a copy of the reference, which points at the same array, so numbers[0] = 99 changes the caller's array. But assigning a new array to numbers only re-points the method's copy of the reference; the caller's arr still points at the original. If you remember "copies of references", you will never be confused by this.

Worked examplesH

A class that protects its invariant

Here is a complete class. Read the Tank class first, then main, which uses it.

java
public class Main {
    public static void main(String[] args) {
        Tank school = new Tank("school roof", 2000);
        Tank clinic = new Tank("clinic", 500, 450);

        double spilled = clinic.collect(120);
        System.out.println(clinic + ", spilled " + spilled + " L");

        school.collect(800);
        double got = school.draw(300);
        System.out.println(school + ", drew " + got + " L");
        System.out.printf("school is %.0f%% full%n", school.percentFull());

        Tank market = new Tank("market: 1500");
        System.out.println(market);
        System.out.println("tanks created: " + Tank.created());

        try {
            new Tank("broken", -5);
        } catch (IllegalArgumentException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }
}

/** A rainwater tank. Its level is always between 0 and its capacity. */
class Tank {
    private static int count = 0;       // one counter shared by the whole class

    private final String name;          // set once, in the constructor
    private final double capacity;
    private double level;               // the only field that changes

    Tank(String name, double capacity, double level) {
        if (capacity <= 0) {
            throw new IllegalArgumentException("capacity must be positive: " + capacity);
        }
        if (level < 0 || level > capacity) {
            throw new IllegalArgumentException("level out of range: " + level);
        }
        this.name = name;
        this.capacity = capacity;
        this.level = level;
        count++;
    }

    Tank(String name, double capacity) {
        this(name, capacity, 0);         // delegate to the main constructor
    }

    /** Parses a description such as "market: 1500". */
    Tank(String description) {
        String[] parts = description.split(":");      // statements before this(...) are new in JDK 25
        if (parts.length != 2) {
            throw new IllegalArgumentException("expected name: capacity, got " + description);
        }
        this(parts[0].strip(), Double.parseDouble(parts[1].strip()), 0);
    }

    /** Adds rain to the tank and returns the litres that overflowed. */
    double collect(double litres) {
        double room = capacity - level;
        double stored = Math.min(litres, room);
        level += stored;
        return litres - stored;
    }

    /** Takes up to the requested litres and returns how many were actually drawn. */
    double draw(double litres) {
        double taken = Math.min(litres, level);
        level -= taken;
        return taken;
    }

    double percentFull() {
        return 100 * level / capacity;
    }

    static int created() {
        return count;
    }

    @Override
    public String toString() {
        return name + ": " + level + "/" + capacity + " L";
    }
}
text
clinic: 500.0/500.0 L, spilled 70.0 L
school roof: 500.0/2000.0 L, drew 300.0 L
school is 25% full
market: 0.0/1500.0 L
tanks created: 3
rejected: capacity must be positive: -5.0

Things to notice, roughly in order of importance:

  • The invariant is enforced in exactly one place per operation. The main constructor refuses impossible tanks by throwing an exception, so an invalid Tank never exists. collect and draw keep the level within bounds and report what happened (the litres spilled, the litres actually drawn) instead of silently ignoring the excess. Because level is private, nothing outside the class can break the rule.
  • final fields can be assigned once, in the constructor, and never again. A tank's name and capacity do not change, so saying so is free documentation that the compiler enforces. Make fields final unless they must change.
  • this.name = name: inside an instance method or constructor, this is the object being worked on. Here it distinguishes the field name from the parameter of the same name.
  • Constructor delegation. Tank(String, double) passes the work to the three-argument constructor with this(...), so validation is written once. The third constructor parses a description first and then delegates. Before JDK 25 that was illegal, because this(...) had to be the first statement; JEP 513 allows statements before it, as long as they do not use the object under construction.
  • static: count is one variable shared by all tanks, and created() is called on the class, Tank.created(). Static methods have no this, so they cannot touch instance fields directly.
  • toString is defined in Object, the ancestor of every class, and returns a string used whenever the object is printed or joined with +. The @Override annotation asks the compiler to check that this method really overrides one from a superclass; a typo such as tostring then becomes a compile error instead of a silent bug.
  • Several classes in one file. Only one top-level class in a file may be public, and it must match the file name. In real projects each top-level class gets its own file.
ComputationC

References, aliasing and null

Now the luggage tags in action. Counter is declared inside a compact source file, so it is nested in the implicit class the compiler creates:

java
class Counter {
    private int value;

    void increment() {
        value++;
    }

    int value() {
        return value;
    }
}

void main() {
    Counter a = new Counter();
    Counter b = a;              // b refers to the same object as a
    Counter c = new Counter();  // a second, separate object

    a.increment();
    b.increment();
    c.increment();

    IO.println("a=" + a.value() + " b=" + b.value() + " c=" + c.value());
    IO.println("a == b: " + (a == b));
    IO.println("a == c: " + (a == c));

    Counter missing = null;
    try {
        missing.increment();
    } catch (NullPointerException e) {
        IO.println(e.getMessage());
    }
}
text
a=2 b=2 c=1
a == b: true
a == c: false
Cannot invoke "Main$Counter.increment()" because "<local4>" is null

a and b are aliases: two references to one object, so both increments land on it. == on references compares identity, whether two references point to the same object, so a == b is true and a == c is false even though c might, at some moment, hold the same count. Comparing objects by their contents is the job of equals, which we study in Exceptions, equality and immutability.

Calling a method through null throws a NullPointerException. Since JDK 14 the message says precisely what was null. Here it says <local4> (the fifth local-variable slot) rather than missing, because the source launcher compiles without debugging information; compiled with javac -g, the same program prints because "missing" is null. Main$Counter is the class's binary name: Counter nested inside Main.

The field value starts at 0 without being assigned. Fields get default values (0, 0.0, false, null); local variables do not, and the compiler rejects any use of a local before it is definitely assigned.

ExplanationH

Designing classes like a professional

Experienced Java developers converge on a handful of habits. None is a law, but each exists because its absence caused real pain.

Start private and final. Make every field private, and final unless it must change. Widen visibility only when something outside genuinely needs it. A small public surface is a promise you can keep.

Do not generate a setter for every field. A class with getLevel() and setLevel(double) for every field is a bag of variables with extra steps; it enforces nothing. Offer operations that mean something in the problem (collect, draw) and let them maintain the invariant. Many classes need no setters at all; immutable classes, whose state never changes after construction, are the easiest of all to reason about and to share between threads.

Validate in the constructor. An object that exists should be valid. Throwing IllegalArgumentException (for bad arguments) or NullPointerException (via Objects.requireNonNull) at construction time puts the error next to its cause, instead of three modules away when the bad value is finally used.

Name methods for what they mean. Java convention: classes are nouns in UpperCamelCase (Tank, HttpClient), methods are verbs or questions in lowerCamelCase (draw, isEmpty, percentFull), constants are UPPER_SNAKE_CASE (MAX_VALUE). Following the convention is not optional in a team; tools and colleagues rely on it.

Prefer static factory methods when a name helps. Tank.ofCubicMetres(2) can say what a constructor cannot, and can return a cached or shared object. The standard library is full of them: List.of, Integer.valueOf, Path.of.

Document the contract. A comment that starts with /** is a Javadoc comment; the javadoc tool turns these into the HTML pages you see in the API documentation. Since JDK 23 you can also write documentation comments in Markdown, as lines starting with ///. Say what a method promises and what it requires, not how it works.

Packages organise classes. In a real project every file starts with a package line (for example package org.example.water;) and its directory path matches the package name. Classes in other packages are used through import lines. Package names are conventionally a reversed domain name the team controls, which keeps them globally unique.

Common misconceptionsH

Common misconceptions

Misconception

"Java passes objects by reference." Java passes references by value. A method can change the object a reference points to, but it cannot make the caller's variable point somewhere else. In a true pass-by-reference language, numbers = new int[...] inside the method would have changed the caller's arr; in Java it does not.

Misconception

"static means constant." It means "belongs to the class rather than to each object". A constant is static final. A mutable static field, like count above, is shared global state, which is convenient in a small program and a frequent source of bugs (especially with threads) in a large one.

Misconception

"Private fields plus public getters and setters is encapsulation." If every field can be set to anything from outside, nothing is protected. Encapsulation means the class's own methods are the only way to change its state, and they keep its invariants.

Misconception

"a == b tells me whether two objects are equal." For references it tells you whether they are the same object. Two separately created objects with identical contents are not ==.

Exercises

Exercises

1. Methods, classes and objects

CoreComputational

StringBuilder is a mutable sequence of characters; String is immutable. What does this program print?

public class Main {
    static void grow(StringBuilder sb, String s) {
        sb.append("!");
        s = s + "!";
    }

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("hi");
        String s = "hi";
        grow(sb, s);
        System.out.println(sb + " " + s);
    }
}

2. Methods, classes and objects

CoreComputational

What does this program print?

class Visit {
    static int total;
    int mine;

    Visit() {
        total++;
        mine++;
    }
}

void main() {
    Visit a = new Visit();
    Visit b = new Visit();
    Visit c = new Visit();
    IO.println(Visit.total * 10 + c.mine);
}

3. Methods, classes and objects

StretchComputational

Three overloads compete for the call kind(5). What does the program print?

public class Main {
    static String kind(long x) { return "long"; }
    static String kind(Integer x) { return "Integer"; }
    static String kind(Object x) { return "Object"; }

    public static void main(String[] args) {
        System.out.println(kind(5));
    }
}

4. Methods, classes and objects

CoreComputational

What does this program print?

void main() {
    int[] a = {1, 2, 3};
    int[] b = a;
    b[1] = 20;
    a = new int[] {7, 8, 9};
    IO.println(a[1] + b[1]);
}

5. Methods, classes and objects

StretchHuman

In JDK 25 a constructor may run statements before calling this(...) or super(...). Which of these may appear in that prologue? Choose all that apply.

Choose all that apply

6. Methods, classes and objects

Warm-upHuman

A Tank must always satisfy 0 ≤ level ≤ capacity. Which design guarantees it?

Choose one

Further reading and resources