Vincent Vauban’s Post

🧩☕ DEFAULT METHODS IN JAVA INTERFACES (SINCE JAVA 8) 🔸 TLDR ▪️ Before Java 8, interfaces could not contain implementations. ▪️ Shared logic required abstract classes. ▪️ Default methods allow behavior directly in interfaces. ▪️ This enables multiple inheritance of behavior and easier API evolution. 🔸 THE PROBLEM BEFORE JAVA 8 Interfaces defined contracts, but could not contain implementations. So developers often created abstract classes to share logic: // Need abstract class to share behavior public abstract class AbstractLogger { public void log(String msg) { System.out.println(timestamp() + ": " + msg); } abstract String timestamp(); } // Single inheritance only public class FileLogger extends AbstractLogger { } The drawback? A class could extend only one abstract class, limiting design flexibility. 🔸 THE MODERN APPROACH (JAVA 8+) Interfaces can now include default implementations. public interface Logger { default void log(String msg) { System.out.println(timestamp() + ": " + msg); } String timestamp(); } // Multiple interfaces allowed public class FileLogger implements Logger, AutoCloseable { } Now classes can compose behavior from multiple interfaces. 🔸 WHY DEFAULT METHODS MATTER ▪️ 🔀 Multiple inheritance of behavior Classes can implement several interfaces that provide functionality. ▪️ 📦 API evolution without breaking code Libraries can add new methods to interfaces without forcing all implementations to change. ▪️ 🧩 Composable design Mix small behavioral interfaces together instead of building deep class hierarchies. 🔸 REAL EXAMPLES IN THE JDK Java itself uses default methods heavily. Examples include: ▪️ Iterable.forEach() ▪️ Map.getOrDefault() ▪️ Collection.removeIf() ▪️ Comparator.thenComparing() These methods were added after Java 8 without breaking existing implementations. 🔸 TAKEAWAYS ▪️ Default methods were introduced in Java 8 (2014) ▪️ They allow interfaces to provide method implementations ▪️ They enable multiple inheritance of behavior ▪️ They helped evolve core Java APIs without breaking compatibility 💬 “Interfaces define the contract. Default methods help evolve that contract safely.” — Inspired by discussions from Brian Goetz, Java Language Architect. #Java #Java8 #Programming #Software src: https://lnkd.in/eWzHA58C Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap

  • default methods in Java interfaces

To view or add a comment, sign in

Explore content categories