Lesson 18 of 20

Static & Final

Static & Final Keywords

Static Fields and Methods

A static member belongs to the class rather than any instance. You access it via the class name:

class Counter {
    static int count = 0;

    Counter() { count++; }

    static int getCount() { return count; }
}

new Counter();
new Counter();
System.out.println(Counter.getCount()); // 2

Static methods cannot access instance fields or use this.

Final Variables

A final variable can only be assigned once. It acts as a constant:

final int MAX = 100;
// MAX = 200;  // compile error!

final String name;
name = "Alice";   // OK — first assignment
// name = "Bob";  // compile error — already assigned

Final Methods and Classes

  • A final method cannot be overridden in a subclass.
  • A final class cannot be extended at all (e.g. String is final).
class Base {
    final void greet() {
        System.out.println("Hello");
    }
}

Static Factory Pattern

Instead of public constructors, use static factory methods for more readable, controlled object creation:

class Color {
    private final int r, g, b;

    private Color(int r, int g, int b) {
        this.r = r; this.g = g; this.b = b;
    }

    static Color of(int r, int g, int b) {
        return new Color(r, g, b);
    }

    static Color red()   { return new Color(255, 0, 0); }
    static Color green() { return new Color(0, 255, 0); }
}

Your Task

  1. Create a class IdGenerator with:

    • A private static int nextId starting at 0
    • A static int generate() method that increments and returns nextId
    • A static void reset() method that sets nextId back to 0
  2. Create a class Temperature with:

    • A private final double value and private final String unit field
    • A private constructor
    • Static factory methods celsius(double v) and fahrenheit(double v)
    • A toString() method returning e.g. "36.6 C" or "98.6 F"
    • A toFahrenheit() method that returns a new Temperature in Fahrenheit (if already F, return itself). Formula: value * 9 / 5 + 32
  3. In main, generate 3 IDs (print each), reset, generate 1 more (print it). Then create a Celsius temperature of 100.0 and a Fahrenheit temperature of 98.6, print both, and convert the Celsius one to Fahrenheit and print it.

TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.