Return to site

[VV127] The Java 21 Newsletter: 💻 Java Interfaces: Can You Override That Method? Let's Set the Record Straight

· java

Interfaces in Java can now do much more than just define abstract methods. Since Java 8+, we can also use default, static, and even private methods — and when interfaces extend each other, you may wonder:

Can this method override that one?

Let’s answer that with a definitive override matrix ✅❌

🧪 Reference Interface

We’ll use this base interface to discuss method overrides:

interface Computer {
    default String getModel() { return "Basic"; }
    static int getRAM() { return 8; }
    String getBrand(); // abstract
    private String getSerial() { return "XYZ123"; }
}

Now, say we create a subinterface:

interface Laptop extends Computer {
    // What can be redefined here?
}

📊 Override Possibilities Matrix

Section image

🔁 Hiding means the static method is not overridden but redefined in the subinterface or implementing class.

💡 Examples

✅ Valid

// default → default
interface Laptop extends Computer {
    default String getModel() { return "Laptop"; }
}

// default → abstract
interface Laptop extends Computer {
    String getModel();
}

// static → static (hiding)
interface Laptop extends Computer {
    static int getRAM() { return 16; }
}

// static → default
interface Laptop extends Computer {
    default int getRAM() { return 16; }
}

// private → anything (in the subinterface)
interface Laptop extends Computer {
    default String getSerial() { return "OverridePrivate"; }
}

❌ Invalid

// default → static ❌
interface Laptop extends Computer {
    static String getModel() { return "Wrong"; } // ❌
}

// abstract → static ❌
interface Laptop extends Computer {
    static String getBrand() { return "Dell"; } // ❌
}

🧠 Key Takeaways

  • You can override abstract or default methods with abstract or default.
  • You cannot override them with static.
  • You can redeclare static or private methods as any type — but they do not override, just hide or coexist.
  • 📌 Private methods are invisible to the subinterface, so any redefinition is treated as a new method.

🧾 Save This Matrix!

Section image

🔖 Tags

#Java #JavaInterfaces #Java8 #Java21 #JavaCertification #OverrideVsHide #SoftwareEngineering #CleanCode #JavaTips #TechInterview

Go further with Java certification:

Java👇

Spring👇