Java's Alternative: Interfaces
Although Java doesn't support extending multiple classes, it offers a workaround through interfaces. An interface is like a contract that specifies what methods a class should implement.
How to Use Interfaces
Declare an interface using the interface keyword. Unlike classes, interfaces can't contain implementation code.
public interface Walks {
void walk();
}
A class can implement an interface using the implements keyword.
public class Human implements Walks {
public void walk() {
System.out.println("Walking...");
}
}
Implementing Multiple Interfaces
The beauty of interfaces is that a single class can implement multiple interfaces.
public interface Eats {
void eat();
}
public class Human implements Walks, Eats {
public void walk() {
System.out.println("Walking...");
}
public void eat() {
System.out.println("Eating...");
}
}
Composition: The Unsung Hero
Another powerful technique to achieve the effect of multiple inheritance is composition.
What is Composition?
Composition involves creating instance variables that refer to other objects. In other words, instead of inheriting features from a parent class, you include instances of the parent class in your new class.
Using Composition
Here's a simple example:
public class Engine {
void start() {
System.out.println("Engine started.");
}
}
public class Car {
// Composition: Car has an Engine
Engine carEngine = new Engine();
void startCar() {
carEngine.start();
}
}
Also see, Java Ioexception
Frequently Asked Questions
Can a class extend multiple classes in Java?
No, a class in Java cannot extend multiple classes because Java does not support multiple inheritance to avoid ambiguity.
How many classes can you extend in Java?
In Java, a class can extend only one class at a time, as Java supports single inheritance for classes.
Can you extend multiple times in Java?
Yes, you can extend multiple times indirectly by creating a chain of inheritance where one class extends another, forming a hierarchy.
Conclusion
While Java doesn't permit extending multiple classes, its design offers alternative ways to mimic the benefits of multiple inheritance. Through the clever use of interfaces and composition, Java provides flexible and clean mechanisms to share behaviors across classes. Understanding these concepts not only clarifies why Java is designed the way it is but also equips you with the tools to build more modular and maintainable applications.
For more information, refer to our Guided Path on Code360 to upskill yourself in Python, Data Structures and Algorithms, Competitive Programming, System Design, and many more!
Head over to our practice platform, Code360, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!