×

java · level 2 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A static field is one box shared by every object.

Each object gets its own fields. Put static in front of a field, though, and there is only one box, kept by the class itself. This is shared, so every object sees the same value. It is handy for counting how many objects were made.

locks a box: once it has a value, it can never change. A static final field is a , like static final int MAX_LIVES = 3;. Constants are named in capitals with underscores, so they stand out.

Try to change a final box and Java refuses to compile, saying it cannot assign a value to that variable.

public class Main {
    static class Ticket {
        static final int PRICE = 8;
        static int sold = 0;
        private int number;
        Ticket() {
            sold++;
            number = sold;
        }
        int getNumber() { return number; }
    }
    public static void main(String[] args) {
        Ticket first = new Ticket();
        Ticket second = new Ticket();
        Ticket third = new Ticket();
        System.out.println("Your ticket is number " + second.getNumber());
        System.out.println(Ticket.sold + " sold, taking " + Ticket.sold * Ticket.PRICE + " pounds");
    }
}

Reach a class variable through the class name, like Ticket.sold.