Search⌘ K
AI Features

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.

AI Powered
Saved
10 attempts left
Reset
Question

What happens if we attempt to override a static method?

You have 10 attempts to answer.

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.

Java
class Language {
static String lang = "Base language";
protected static void printLanguage() {
System.out.println(lang);
}
protected Language sayHello() {
System.out.println("----");
return this;
}
}
class Spanish extends Language {
static String lang = "Spanish";
protected static void printLanguage() {
System.out.println(lang);
}
@Override
protected Spanish sayHello() {
System.out.println("¡Hola!");
return this;
}
}
  • Lines 1–6: The Language class declares a static field lang and a static method printLanguage(). Because the method is static, it belongs to the class itself rather than to its instances.

  • Lines 9–11: The ...