Static, Overriding and Hiding Puzzles
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Inheritance puzzles ask what prints when a parent reference holds a child object. The interviewer is checking whether you can tell what Java decides at compile time from the variable's type, and what it decides at runtime from the real object.
Static method hiding vs instance overriding
Dynamic dispatch is choosing which instance method runs from the object's real class at runtime, so Parent p = new Child(); p.show() runs Child.show(). Static methods and fields are not dispatched.
Employee and Manager both declare a static company() and an instance role(). The program calls them through an Employee reference that holds a Manager, then through a Manager reference.
Example 1 · Static hides, instance overrides
class Employee { static String company() { return "Employee.company (static)"; }
String role() { return "Employee.role"; }}
class Manager extends Employee { static String company() { return "Manager.company (static)"; }
@Override String role() { return "Manager.role"; }}
public class HidingDemo { public static void main(String[] args) { Employee e = new Manager(); System.out.println(e.company()); System.out.println(e.role());
Manager m = new Manager(); System.out.println(m.company()); System.out.println(((Employee) m).company()); }}Employee.company (static) Manager.role Manager.company (static) Employee.company (static)
What this code does
eis declared asEmployee, so the static call is bound toEmployee.company()at compile time; the object being a Manager does not matter.role()is an instance method, so the Manager object's version runs. Castingmto Employee changes the static call, never an overridden one.
A static method with the same signature in the child does not override the parent's one; it hides it, and the call is bound at compile time from the declared type. The rules:
- Instance method: the real object's class (runtime).
- Static method: the declared type of the variable (compile time).
privateandfinalmethods are never overridden.@Overrideon a static method does not compile.
Revise: Method overriding (opens in a new tab) and Dynamic method dispatch (opens in a new tab).
Fix the error
Fix the overriding error
Read the error, then pick the line that fixes it.
Round 1 of 2
A static method tries to replace an instance method.
Error
Staffing.java:6: error: role() in Manager cannot override role() in Employee overriding method is static
Field hiding: fields are not polymorphic
Hiding is when a child declares a static method or a field with the same name as the parent's. Both exist, and the one used is chosen at compile time from the declared type, not from the object.
A Child object holds two fields called name. The program reads them through a Parent reference, through a Child reference and through getters.
Example 2 · Two fields named name in one object
class Parent { String name = "Parent field";
String getName() { return name; }}
class Child extends Parent { String name = "Child field";
@Override String getName() { return name; }
String both() { return super.name + " / " + this.name; }}
public class FieldHidingDemo { public static void main(String[] args) { Parent p = new Child(); System.out.println(p.name); System.out.println(p.getName()); System.out.println(((Child) p).name); System.out.println(((Child) p).both()); }}Parent field Child field Child field Parent field / Child field
What this code does
- Field access uses the declared type:
pis aParentvariable, sop.nameis the parent's field. getName()is overridden and dispatched at runtime, so it returns the child's field.super.namereaches the hidden parent field.
A getter is an instance method, so it is overridden and chosen at runtime: p.getName() returns the child's value even through a Parent reference. Inside the child, super.name reaches the hidden parent field. In real code, never hide fields.
Revise: Field hiding vs method overriding (opens in a new tab).
Find the bug
Why the parent's value?
Tap the line that gives the wrong result.
It should print Meena but prints Staff.
Round 1 of 2A constructor calling an overridden method
Default values are what fields hold before any initialiser runs: 0 for numbers, false for booleans and null for objects. A parent constructor that calls an overridden method sees the child's fields at these values.
Device calls describe() from its constructor, and Phone overrides describe() to print its own fields. Predict what new Phone(...) prints.
Example 3 · The overridden call that sees default values
class Device { Device() { System.out.println("Device constructor"); describe(); // calls the CHILD's version }
void describe() { System.out.println("Device describe"); }}
class Phone extends Device { private String model = "Pixel"; private int ram = 8;
Phone() { super(); System.out.println("Phone constructor: " + model + ", " + ram + " GB"); }
@Override void describe() { System.out.println("Phone describe: " + model + ", " + ram + " GB"); }}
public class ConstructorCallDemo { public static void main(String[] args) { new Phone(); }}Device constructor Phone describe: null, 0 GB Phone constructor: Pixel, 8 GB
What this code does
describe()is dispatched to Phone's version, but Phone's field initialisers have not run yet, somodelis stillnullandramis 0.- After
super()returns, the fields get "Pixel" and 8, and the Phone constructor body sees the real values.
The parent constructor runs first, before the child's fields get their initial values, so the child's version of the method sees 0, false or null even when the field has an initialiser. In real code, constructors should call only private, final or static methods.
Revise: Constructor execution in inheritance (opens in a new tab).
Trace the code
Watch new Phone() run
Variables
- storage
- 0
Output
(nothing printed yet)Line 11new Phone() makes the object. Its field storage starts at the default 0.
Initialization order across parent and child
A static initialiser is a static { ... } block that runs once, when the class is first initialised. An instance initialiser is a plain { ... } block that runs for every new object, before the constructor body.
Parent and Child each have a static block, an instance block and a constructor, and main creates two Child objects. The class with main has a static block too.
Example 4 · Who prints first? Static, instance, constructor
class Parent { static { System.out.println("Parent static block"); }
{ System.out.println("Parent instance block"); }
Parent() { System.out.println("Parent constructor"); }}
class Child extends Parent { static { System.out.println("Child static block"); }
{ System.out.println("Child instance block"); }
Child() { System.out.println("Child constructor"); }}
public class InitOrderDemo { static { System.out.println("InitOrderDemo static block"); }
public static void main(String[] args) { System.out.println("main starts"); new Child(); System.out.println("--"); new Child(); }}InitOrderDemo static block main starts Parent static block Child static block Parent instance block Parent constructor Child instance block Child constructor -- Parent instance block Parent constructor Child instance block Child constructor
What this code does
- The main class is initialised before
main, and Parent and Child are initialised on first use, parent first. Static blocks run only once. - Each
new Child()runs the parent's instance block and constructor, then the child's. The second object repeats only these instance steps.
The class with main is initialised before main runs, so its static block prints first. Creating a second object repeats only the instance steps; static blocks never run again.
Order of execution
The first new Child()
Tap the steps in the order Java runs them.
Static counter shared across instances
A static variable belongs to the class, not to an object, so every object shares one copy. An instance variable gives each object its own copy.
Each Ticket constructor adds 1 to a static counter. The program prints ticket numbers and counter values through different objects, even through a null reference.
Example 5 · One static counter, many tickets
class Ticket { static int issued = 0; int number;
Ticket() { issued++; number = issued; }}
public class StaticCounterDemo { public static void main(String[] args) { Ticket a = new Ticket(); Ticket b = new Ticket(); Ticket c = new Ticket(); System.out.println(a.number + " " + b.number + " " + c.number); System.out.println(Ticket.issued + " " + a.issued + " " + c.issued);
a.issued = 10; System.out.println("c.issued after a.issued = 10: " + c.issued);
Ticket none = null; System.out.println("Through a null reference: " + none.issued); }}1 2 3 3 3 3 c.issued after a.issued = 10: 10 Through a null reference: 10
What this code does
- Each ticket keeps its own
number, but there is only oneissued, so every reference shows the latest value. none.issuedcompiles toTicket.issued, so it works even thoughnoneis null; an instance field through null would throw.
You can read a static field through an object reference, even a null one, because the compiler replaces the reference with the class name. It compiles and throws nothing, which surprises many candidates. Prefer Ticket.issued, so the code says what it means.
Predict the output
One copy or many?
Read each program and pick what it prints.
Round 1 of 3
A counter shared by every object.
Next step
Check your understanding
12 quick questions