Wednesday, 13 January 2016

Java Tutorial : Implementing two Interfaces

Loved This Java Tutorial? Support Ram N Java!

Subscribe to the channel for step-by-step, beginner-friendly core Java tutorials and examples.

SUBSCRIBE ON YOUTUBE

Multiple Inheritance Through Interfaces in Java

In Java, a class cannot inherit from more than one class directly (avoiding the classic "Diamond Problem"). However, real-world software often requires a class to fulfill multiple roles simultaneously.

Java solves this elegantly by allowing a single class to implement two or more interfaces. This gives you all the benefits of multiple inheritance while keeping your code clean and ambiguity-free.

Syntax for Implementing Multiple Interfaces

To implement two interfaces, simply separate their names with a comma after the implements keyword:

public class Student implements Person, Learner {
  @Override
  public void walk() {
    System.out.println("Student is walking");
  }

  @Override
  public void study() {
    System.out.println("Student is studying");
  }
}
  • Comma-Separated List: You can chain as many interfaces as your class needs: implements InterfaceA, InterfaceB.
  • Full Contract Fulfillment: The implementing class must override and supply concrete bodies for all abstract methods declared in every listed interface.
  • Public Access: Overridden methods must explicitly carry the public modifier.

Working with Multiple Interface References

When an object implements two interfaces, you can treat it as an instance of either type using polymorphism:

Person p = new Student();
p.walk(); // Accessible via Person reference

Learner l = new Student();
l.study(); // Accessible via Learner reference

This gives you exceptional flexibility when passing objects into methods that only care about specific capabilities rather than the full concrete type.

What Happens If Both Interfaces Share the Same Method?

If both interfaces declare an abstract method with the exact same name and parameter list, your implementing class provides a single implementation that fulfills the contract for both interfaces at once.

Key Takeaways for Beginners

  • Java classes support single class inheritance, but multiple interface implementation.
  • Always implement every abstract method, or declare the class abstract.
  • Use the @Override annotation to safeguard against signature mismatches.

No comments:

Post a Comment

Tutorials