Jack Ng

Essay

Learning Java, Part 4: Classes, Objects and Methods

Study notes on defining a class, creating objects with new, reference variables, methods with parameters and return values, constructors, this, and garbage collection. Written entirely by an AI model.

This is the part where Java becomes Java. Everything from here on is about designing classes. Part 6 of the Python series introduced classes as a way to bundle data with the code that uses it; Java uses the same idea, but declares the data up front.

A class is a template

A class describes what every object of that kind holds (its fields, also called instance variables) and what it can do (its methods). An object is one instance made from that template.

class Kettle {
    int capacityMl;     // fields
    int waterMl;

    void fill(int ml) {                 // a method
        waterMl = Math.min(capacityMl, waterMl + ml);
    }

    int cupsAvailable() {               // returns a value
        return waterMl / 250;
    }
}

public class KettleDemo {
    public static void main(String[] args) {
        Kettle k = new Kettle();
        k.capacityMl = 1700;
        k.fill(1000);
        k.fill(1000);
        System.out.println(k.waterMl + " ml, " + k.cupsAvailable() + " cups");
    }
}
1700 ml, 6 cups
  • Two classes can sit in one file, but only one may be public, and the file is named after it.
  • Inside a method, a bare field name like waterMl means “this object’s waterMl”. Python spells that self.water_ml; Java lets you leave out the this..
  • Methods are declared with a return type (int) or void, then the name and the parameter list. Every parameter has a type.
  • The dot operator reaches a member: k.fill(1000), k.waterMl.

Fields get default values: 0 for numbers, false for boolean, '\u0000' for char and null for references. Local variables inside methods get none and must be assigned first.

new and references

new Kettle() creates an object on the heap and gives back a reference to it. The variable k holds that reference, not the object itself. This matters as soon as you copy a variable:

class Cup {
    int sugar;
}

public class References {
    public static void main(String[] args) {
        Cup a = new Cup();
        Cup b = a;          // copies the reference: one cup, two names
        b.sugar = 2;
        System.out.println(a.sugar);

        Cup c = new Cup();  // a second, separate cup
        System.out.println(a == b);
        System.out.println(a == c);

        b = null;           // b no longer refers to anything
        System.out.println(a.sugar);
    }
}
2
true
false
2

This is exactly how Python names work, so it should feel familiar. == on references asks “same object?”, not “same contents?”. Part 5 returns to this with strings.

Calling a method through a null reference throws a NullPointerException, the most common Java runtime error. The message names the variable that was null.

Methods: parameters and return

class Recipe {
    double ratio(double tea, double water) {
        if (water == 0) return 0;     // early return
        return tea / water;
    }
}

public class RecipeDemo {
    public static void main(String[] args) {
        Recipe r = new Recipe();
        System.out.println(r.ratio(3, 250));
        System.out.println(r.ratio(3, 0));
    }
}
0.012
0.0
  • An argument is the value passed in; a parameter is the variable that receives it.
  • A non-void method must return a value of its type on every path; the compiler checks this. A void method can use a bare return; to finish early.
  • The compiler also rejects unreachable code, such as a statement after return.

Constructors

Setting fields one by one after new is clumsy and easy to forget. A constructor runs when the object is created and puts it into a valid starting state. It has the same name as the class and no return type, not even void.

class Teapot {
    String name;
    int cups;

    Teapot(String name, int cups) {
        this.name = name;      // this.name is the field; name is the parameter
        this.cups = cups;
    }

    String describe() {
        return name + " (" + cups + " cups)";
    }
}

public class TeapotDemo {
    public static void main(String[] args) {
        Teapot small = new Teapot("Blue", 2);
        Teapot large = new Teapot("Iron", 6);
        System.out.println(small.describe());
        System.out.println(large.describe());
    }
}
Blue (2 cups)
Iron (6 cups)
  • It is Python’s __init__, with the object passed implicitly.
  • If you write no constructor, Java supplies a default one with no parameters that leaves fields at their defaults. As soon as you write any constructor, that default disappears, so new Teapot() would no longer compile here.
  • Part 6 shows how to write several constructors for one class.

The this keyword

this is the object a method was called on. It has three uses:

  1. Telling a field from a parameter of the same name, as in this.name = name. Without this, name = name assigns the parameter to itself and the field stays null. That bug compiles.
  2. Passing the current object to another method: register(this).
  3. Calling another constructor of the same class: this(name, 1); (Part 6).

Garbage collection

Java has no delete. When no reference to an object remains, it becomes eligible for garbage collection, and the JVM reclaims the memory at some later time of its choosing. In the earlier example, a Cup that no variable refers to is garbage.

  • You cannot force collection. System.gc() is only a hint.
  • The book describes finalize(), a method the collector would call before reclaiming an object. It has been deprecated for removal since Java 18, because there was no guarantee it would run at all, or when. Do not use it.
  • To release a resource such as a file at a known moment, use try-with-resources (Part 10).

Designing a class

When you design a class, two questions shape it:

  • What does each object need to remember? Those become fields.
  • What should it answer or do? Those become methods.

A class should model one idea. Its constructor should leave it valid, and its methods should keep it valid. Part 6 adds the tool that enforces that: making fields private.

Exam-style checks

  • Explain the difference between a class and an object, with a five-line example.
  • What happens in memory when you write Cup b = a;? What does a == b test?
  • Why does name = name; inside a constructor compile but leave the field unset?
  • When is the default constructor provided, and when does it disappear?
  • When does an object become eligible for garbage collection?

Where to practise

Schildt’s Chapter 4 builds a Vehicle class step by step, then turns the Chapter 3 help system into a Help class. Do the same with something of your own: a BankAccount with an owner, a balance, a constructor, deposit, withdraw (refusing to go below zero) and a method that returns a one-line summary. Then make two accounts and copy one reference to a third variable to see sharing in action.