Calling an override before field initialization

A storage dashboard records available space when its monitor is constructed, then requests a fresh reading. Trace this Java program:


Java
class StorageMonitor {
    private int storedAvailableMiB;

    public StorageMonitor() {
        storedAvailableMiB = availableMiB();
    }

    public int availableMiB() {
        return 128;
    }

    public int storedAvailableMiB() {
        return storedAvailableMiB;
    }
}

class ReservedStorage extends StorageMonitor {
    private int reservedMiB = 24;

    @Override
    public int availableMiB() {
        return 128 - reservedMiB;
    }
}

class Demo {
    public static void main(String[] args) {
        StorageMonitor monitor = new ReservedStorage();
        System.out.println(monitor.storedAvailableMiB());
        System.out.println(monitor.availableMiB());
    }
}


Java gives instance int fields the default value 0 before constructor code runs. A subclass's field initializer runs after its superclass constructor returns.


Report the stored available space printed by the first statement and the fresh available space printed by the second statement. Give both in MiB, as exact integers with zero decimal places.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Method Overriding Questions: