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

java
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

java
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)

java
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 time

Enums — type-safe constants

java
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:

java
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