Core Java

core27StaticMembersDemo

Path
pkg1core/core27StaticMembersDemo.java
Package
pkg1core
Study order
26
Run
Single-file source launch
Command
java pkg1core/core27StaticMembersDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core27StaticMembersDemo.java
1package pkg1core;2 3/*4 * core27StaticMembersDemo.java5 * ----------------------------6 * Static fields, static methods, static blocks, and method hiding.7 *8 * EXPLANATION:9 *  - `static` belongs to the CLASS, not any single object.10 *  - Static methods cannot use `this` or access instance fields directly.11 *  - Static initializer blocks run once when the class is first loaded.12 *  - Subclass static methods HIDE (not override) parent static methods.13 */14public class core27StaticMembersDemo {15 16    static class Counter {17        static int totalCreated = 0;          // shared across all instances18        final int instanceId;19 20        static {                              // runs once at class load21            System.out.println("  [static block] Counter class loaded");22        }23 24        Counter() {25            totalCreated++;26            instanceId = totalCreated;27        }28 29        static int getTotal() { return totalCreated; }30 31        static void reset() { totalCreated = 0; }  // affects all instances' shared state32    }33 34    static class Parent  { static String greet() { return "Parent"; } }35    static class Child extends Parent { static String greet() { return "Child"; } }  // hides, not overrides36 37    public static void main(String[] args) {38        Counter c1 = new Counter();39        Counter c2 = new Counter();40        System.out.println("instance ids: " + c1.instanceId + ", " + c2.instanceId);41        System.out.println("total created: " + Counter.getTotal());42 43        Parent p = new Child();44        System.out.println("static hiding: p.greet()=" + p.greet() + " Child.greet()=" + Child.greet());45 46        Counter.reset();47        System.out.println("after reset: " + Counter.getTotal());48    }49}