Inheritance Gotchas
Explore the common pitfalls of inheritance in Java by learning how JVM resolves overridden and hidden methods, the rules around access modifiers, covariant return types, and method resolution in interface hierarchies. Understand how these nuances impact runtime behavior and avoid subtle bugs in your code.
We'll cover the following...
Mastering foundational class hierarchies allows us to build clean applications. However, technical interviews frequently focus on subtle edge cases where object-oriented mechanics behave counterintuitively.
Let's analyze these common inheritance traps and explore how to avoid them.
What happens if we attempt to override a static method?
The crucial difference lies in how the JVM resolves the method call. Overridden instance methods are resolved dynamically at runtime based on the actual object instance in memory. Hidden static methods are resolved statically at compile-time based entirely on the declared type of the reference variable.
To see this distinction in action, let us review a classic interview setup where a subclass attempts to redefine both static and instance methods of its base class.
Lines 1–6: The
Languageclass declares a static fieldlangand a static methodprintLanguage(). Because the method is static, it belongs to the class itself rather than to its instances.Lines 9–11: The ...