java · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Bake and bite some cookies. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class Cookie {
static int baked = 0;
int bites = 0;
Cookie() {
baked++;
}
void bite() { bites++; }
}
public static void main(String[] args) {
Cookie first = new Cookie();
Cookie second = new Cookie();
Cookie third = new Cookie();
first.bite();
second.bite();
second.bite();
System.out.println(Cookie.baked + " baked, " + second.bites + " bites");
}
}
your turn
Your turn. Set the speed limit.
Choose a speed limit, as a whole number, on line 2. Then press run to check three cars against it.
output
press run to see what happens
fix it
Someone tried to bend the rules. Fix it!
output
press run to see what happens
- Java says it
cannot assign a valuetoMAX_PLAYERSon line 5. MAX_PLAYERSisfinal, so it can never change. The game only has room for 4, and line 5 tries to cheat.- Delete line 5, then press run.
nailed it
you shared one box between objects. :D
- A
staticfield is one box shared by the whole class. finallocks a value so it never changes.- Name constants in capitals, like
MAX_LIVES.
new words in your collection
- class variable
- final
- constant
This lesson isn’t saved. A free account remembers every lesson you finish.