← Back to Week 5

Static Classes — the Math pattern

A static class is a library of related functions, not a thing you create with new. Java's Math class is the canonical example.

π
java.lang.Math
Static class — no instances allowed
public static final double PI = 3.14159265...;
public static final double E  = 2.71828182...;
public static double sqrt(double a) // → double
public static double pow(double a, double b) // → double
public static double floor(double a) // → double
public static double ceil(double a) // → double
public static long round(double a) // → long
public static double abs(double a) // → double
public static double max(double a, double b) // → double
public static double min(double a, double b) // → double
✕ Cannot do this
Math m = new Math();
The constructor is private, so the compiler won't let you.
Live Examples
Math.PI 3.141592653589793
Math.sqrt(25) 5.0
Math.pow(5, 2) 25.0
Math.floor(12.8) 12.0
Math.ceil(12.2) 13.0
Math.round(12.5) 13
Math.abs(-7.3) 7.3
Math.max(10, 25) 25.0
Try it: Area of a circle = Math.PI * Math.pow(r, 2)
radius = → area =
When to make a static class: when you have a group of helper functions that don't need any per-instance data — just inputs and outputs. A name formatter. A unit converter. A pricing rule library. The recipe is always the same: every member is static, the constructor is private (so nobody can new it), and consumers call ClassName.method() directly.
← Instance vs Static Members Has-A Relationship →