Achieving Inheritance in Java Without Extends

Java Trick Question: Inheritance Without extends? A few days ago, I came across an interview question that made me pause: 👉 “Can you achieve inheritance in Java without using the extends keyword?” At first glance, it feels like a trick — because we’re so used to extends for classes and implements for interfaces. But here’s the twist 👇 💡 Yes, you can — through composition and interface inheritance! For example: interface Animal { void sound(); } class Dog implements Animal { public void sound() { System.out.println("Woof!"); } } Here, Dog inherits behavior from Animal — but there’s no extends in sight. That’s interface-based inheritance. And there’s more — You can also achieve reuse (a form of inheritance) using composition, by including an object of another class inside your class and delegating behavior to it. Example: class Engine { void start() { System.out.println("Engine started"); } } class Car { private Engine engine = new Engine(); void start() { engine.start(); } // Behavior reuse without 'extends' } 🔹 No extends. 🔹 Yet, functionality is “inherited.” 🔹 This is known as composition over inheritance — one of the key design principles in OOP. So next time someone asks, “Can you achieve inheritance without extends?” You can confidently say: “Yes — through interfaces and composition!” 💪 #Java #OOP #Inheritance #InterviewQuestion #Developers #LearningEveryday

  • graphical user interface, diagram

To view or add a comment, sign in

Explore content categories