Static, Overriding and Hiding Puzzles
40 min · Intermediate
Inheritance puzzles come down to one question: is the choice made at compile time from the variable's declared type, or at runtime from the real object? Only instance methods are chosen at runtime. Static methods, fields and overloads are all chosen at compile time.
Topics in this lesson
- Static method hiding vs instance overriding
- Field hiding: fields are not polymorphic
- A constructor calling an overridden method
- Initialization order across parent and child
- Static counter shared across instances
Interview questions this lesson answers
- With
Parent p = new Child();and an overridden instance methodshow(), whichshow()runs? - What is method hiding?
- Does
@Overrideon a static method in the child compile? - Parent p = new Child(); p.staticMethod() — which version runs?
- Can a static method in the child hide an instance method of the parent?
- Are fields polymorphic in Java?
- How do you access a hidden parent field from the child?
- Why should constructors not call overridable methods?
- What does a parent constructor see when it calls an overridden method that reads a child field?
- What is the order of initialization when you create a child object?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.