Wednesday, 13 January 2016

Java Tutorial : Implementing an Interface and extends class

Master Core Java Step-by-Step!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!

Subscribe Now on YouTube

Extending a Class and Implementing an Interface Simultaneously

In Java, object-oriented design often requires a class to inherit base state and functionality from a parent class while simultaneously adhering to one or more behavioral contracts.

Java makes this possible by allowing a single class to combine class inheritance and interface implementation in one declaration line using both the extends and implements keywords together.

Why Combine extends and implements?

Combining both approaches brings the best of both worlds:

  • Code Reusability via Inheritance: Inherit common attributes, state, and concrete methods from a base class without rewriting them.
  • Design Flexibility via Interfaces: Implement interface contracts so your class can participate in multiple polymorphic hierarchies cleanly.
  • Single Class Limitation Workaround: While Java restricts classes to extending only one superclass, you can implement as many interfaces as necessary alongside that single parent class.

Code Example: Class Inheritance with Interface Implementation

// Superclass
class Person {
  String name = "Alex";
  void showName() {
    System.out.println("Person Name: " + name);
  }
}

// Interface
interface Worker {
  void doWork();
}

// Subclass extending Person and implementing Worker simultaneously
class SoftwareEngineer extends Person implements Worker {
  @Override
  public void doWork() {
    System.out.println("Writing and debugging Java code.");
  }
}

public class Test {
  public static void main(String[] args) {
    SoftwareEngineer dev = new SoftwareEngineer();
    dev.showName(); // Inherited from Person
    dev.doWork(); // Implemented from Worker
  }
}

Output:

Person Name: Alex
Writing and debugging Java code.

Important Syntax and Design Rules

  1. Keyword Order Matters: The extends keyword must always appear before implements in the class declaration: class SubClass extends SuperClass implements Interface1, Interface2.
  2. Single Extension Rule: A class can extend only one superclass, but it can implement multiple comma-separated interfaces.
  3. Contract Fulfillment: The concrete subclass must provide method bodies for all abstract methods declared in the implemented interfaces unless it is declared as an abstract class.

Watch More Java Inheritance & Interface Tutorials:

No comments:

Post a Comment

Tutorials