Core Java
14 — Static Members & Enums
Previous: 13 Abstraction & Interfaces · Next: 15 Records & Sealed
▶️ java pkg1core/core27StaticMembersDemo.java · java pkg1core/core15EnumsDemo.java
Static — belongs to the class
1class Counter {2 static int total = 0; // shared by ALL instances3 int id;4 5 Counter() { total++; id = total; }6 static int getTotal() { return total; }7}| Static | Instance |
|---|---|
| One copy per class | One copy per object |
Called via Class.method() |
Called on object |
Can't use this |
Has this |
Static initializer block
1static {2 System.out.println("Class loaded — runs once");3}Runs when the class is first loaded by the JVM.
Static method hiding (not overriding)
1class Parent { static String greet() { return "P"; } }2class Child extends Parent { static String greet() { return "C"; } }3 4Parent p = new Child();5p.greet(); // "P" — resolved by reference type at compile timeEnums — type-safe constants
1enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }2 3Day today = Day.MON;4if (today == Day.SAT) { ... }5 6for (Day d : Day.values()) System.out.println(d);Enums can have fields, constructors, and methods:
1enum Planet {2 EARTH(5.97e24),3 MARS(6.39e23);4 final double mass;5 Planet(double mass) { this.mass = mass; }6}💡 Best singleton in Java: enum Instance { INSTANCE; }
Next → 15 Records & Sealed Related → 01 Core Java
Source named in this chapter
- core27StaticMembersDemopkg1core/core27StaticMembersDemo.java
- core15EnumsDemopkg1core/core15EnumsDemo.java