Matheion

MA-JAVA0 · Module 6

Java classes and objects

Topics: class · new · Fields · Methods on objects

Overview

Session 6 — Java classes and objects

You will define a simple class, construct instances with new, store state in fields, and call instance methods. This matches the usual “intro to Java classes” week after arrays and loops.

Time: about 80 minutes.

Concepts

1. Class = blueprint, object = instance

A class declares fields (per-object state) and methods (behaviour). Creating an object uses new, which allocates memory and runs a constructor (Session 8 deep dive—here constructors may be implicit default).

public class StepCounter {
    int total;

    void add(int delta) {
        if (delta > 0) {
            total += delta;
        }
    }

    int current() {
        return total;
    }
}

Usage:

StepCounter morning = new StepCounter();
morning.add(1200);
System.out.println(morning.current());

morning is a reference variable; new StepCounter() builds the object in the heap.


2. this (preview)

Inside instance methods, this refers to the receiver object. Writing this.total disambiguates field names from parameters—Session 8 uses this heavily.


3. Aliasing

Two variables can reference the same object:

StepCounter a = new StepCounter();
StepCounter b = a;
b.add(500);
System.out.println(a.current()); // 500 — same object mutated

Draw boxes when confused: one object, two arrows.


4. null

A reference variable may hold null, meaning “points nowhere.” Calling a method or field on null throws NullPointerException. Always check or guarantee assignment before use.


5. == vs .equals reminder

For primitives, == compares values. For references, == compares addresses. Two distinct String objects with the same text may compare false under == but true under .equals—prefer .equals for text.


6. Why not everything static?

static members belong to the class, not each instance. Use instance fields when each object carries its own lifecycle (StepCounter totals). Reserve static for shared constants and utility functions until the design demands otherwise.

Examples

Example A — two independent counters

Use the StepCounter class from the concept section. A small driver file looks like this:

public class CounterLab {
    public static void main(String[] args) {
        StepCounter left = new StepCounter();
        StepCounter right = new StepCounter();
        left.add(100);
        right.add(250);
        System.out.println(left.current());  // 100
        System.out.println(right.current()); // 250
    }
}

Save StepCounter in StepCounter.java and CounterLab in CounterLab.java. Java allows only one public top-level class per file, so each public class gets its own filename.

If you want one paste-and-run file for a quick lab, put a package-private top-level class in the same file—still no nesting:

class StepCounter {
    int total;

    void add(int delta) {
        if (delta > 0) {
            total += delta;
        }
    }

    int current() {
        return total;
    }
}

public class CounterLab {
    public static void main(String[] args) {
        StepCounter left = new StepCounter();
        StepCounter right = new StepCounter();
        left.add(100);
        right.add(250);
        System.out.println(left.current());  // 100
        System.out.println(right.current()); // 250
    }
}

Name the file CounterLab.java (matching the public class). StepCounter is visible in that file because it sits at the top level, not inside another class.


Example B — accidental sharing

Reuse the same StepCounter class. Only the driver changes:

public class AliasLab {
    public static void main(String[] args) {
        StepCounter first = new StepCounter();
        StepCounter second = first; // alias — both names point at one object
        second.add(10);
        System.out.println(first.current()); // 10
    }
}

If you intended two separate counters, allocate with new StepCounter() twice instead of assigning one reference to another.

Bridge

Objects ↔ later topics

  1. Encapsulation (Session 7) hides fields so aliases cannot violate invariants casually.

  2. Collections store references to objects—aliasing patterns repeat at scale.

  3. Testing frameworks assert object behaviour via public methods—design APIs accordingly.

  4. Graph algorithms reuse “node with neighbours” mental models—objects are nodes, references edges.

When you sketch objects before coding, class design becomes calmer.

Practice check — classes and objects

Multiple-choice check from the Matheion app lesson. Pick an answer for each question, then submit.

  1. 1.After `StepCounter c = new StepCounter(); StepCounter d = c; d.add(5);`, what does `c.current()` reflect?

  2. 2.What does `new` do when you write `Student s = new Student("Ada");`?

  3. 3.Why is `==` risky for comparing two `String` values typed by a user?

  4. 4.Fields without an explicit initialiser in a new object: what is an `int` field's default?

  5. 5.Which statement best describes a class vs an object?