RIDDHI RADIA’s Post

A Java concept that confused me at first: Why were default methods introduced in interfaces? Before Java 8, interfaces could only have: • method declarations (no implementation) Which meant: If you added a new method to an interface, every class implementing it would break. Example: interface PaymentService {   void pay(); } Now if you add: void refund(); All existing classes must implement refund() ❌ This becomes a problem in large systems. 👉 Solution: Default Methods (Java 8) Default methods allow interfaces to provide a default implementation. Example: interface PaymentService {   void pay();   default void refund() {     System.out.println("Default refund logic");   } } Now: • Old classes don’t break ✅ • New behavior can be added safely ✅ 👉 Internal idea (simple) A default method is just a method inside an interface with a body that implementing classes can use or override. 👉 Why this matters It allows Java to evolve without breaking existing code. A simple example is forEach(). It was added later to the Iterable interface, but all existing collection classes could use it without any changes. That’s how default methods help Java grow without breaking old code. Small design decisions like this make a big difference in real systems. Had you faced issues while modifying interfaces in your projects? #Java #BackendEngineering #Java8 #SoftwareEngineering #LearningInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories