Skip to content
Codewilds

Lesson 20 of 34 · Classes & Objects

Java static vs Instance Members

medium20 XP3 min read

Every hero has their own health, but how many heroes exist in total? That number does not belong to any single hero — it belongs to the Hero class as a whole. The static keyword marks exactly those class-level members.

Instance fields vs static fields

class Hero {
    static int created = 0;   // one counter, shared by the whole class
    String name;              // every hero has its own name

    Hero(String name) {
        this.name = name;
        created++;
    }
}

new Hero("Aria");
new Hero("Bram");
System.out.println(Hero.created);
2

An instance field exists once per object: two heroes, two names. A static field exists once per class, no matter how many objects you create — even zero. You reach it through the class name: Hero.created.

Static methods

A static method also belongs to the class, so you call it without an object. You have used them since your very first lesson: Math.max(3, 9), Integer.parseInt("42"), String.valueOf(7) — and every method you wrote in Main, including main itself.

class Temperature {
    static double toFahrenheit(double celsius) {
        return celsius * 9 / 5 + 32;
    }
}

double f = Temperature.toFahrenheit(25);   // 77.0 — no object needed

Static methods are ideal for utilities that depend only on their parameters, and for counters and factories that work with static fields.

Why static methods can't use instance fields

A static method runs without any particular object, so it has no this. Which hero's name should it read? Java refuses to guess:

class Hero {
    String name;

    static void shout() {
        System.out.println(name);
        // compile error: non-static variable name cannot be referenced from a static context
    }
}

The other direction is fine: instance methods may read static fields and call static methods freely.

Constants: static final

A value that is the same for everyone and never changes is declared static final and named in UPPER_SNAKE_CASE:

class Shop {
    static final int MAX_STACK = 64;
    static final double TAX_RATE = 0.2;
}

System.out.println(Shop.MAX_STACK * 2);   // 128

The JDK is full of such constants: Math.PI, Integer.MAX_VALUE.

Common mistakes

  • Making a field static by accident. If name were static, all heroes would share one name — renaming one hero renames them all.
  • Calling instance methods from main without an object. main is static; create an object first and call the method on it.
  • Reaching static members through an object (aria.created). It compiles, but it hides the fact that the value is shared. Write Hero.created.
  • Using static fields as global variables for everything. Shared, changeable state makes programs hard to follow — keep static for things that truly belong to the class.

Assignment

Complete the class Ticket for the Highland Games:

  • static final int PRICE = 25; — already given
  • private static int issued — how many tickets have been created so far
  • private instance fields final int number and final String holder
  • Ticket(String holder) — counts the new ticket and gives it the next number: the first ticket ever is number 1, the next one number 2, and so on
  • instance methods int getNumber(), String getHolder() and String label(), which returns the holder followed by the formatted number, e.g. "Aria T-0007"
  • static methods int getIssuedCount(), int totalRevenue() (tickets issued × PRICE) and String formatNumber(int number), which returns "T-" plus the number padded with zeros to 4 digits: formatNumber(7) → "T-0007"
Ticket first = new Ticket("Aria");
Ticket second = new Ticket("Bram");
first.getNumber();          // 1
second.label();             // "Bram T-0002"
Ticket.getIssuedCount();    // 2
Ticket.totalRevenue();      // 50

All tests run in one program and share the static counter, so they check how values change — for example that the count goes up by exactly one.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Static members in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+20 XP

Lesson 20 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.