More about Interfaces

An interface in Java is a reference type that consists of abstract methods, constants, static methods, and, since Java 8, default methods. It provides a blueprint for a class to implement, defining a set of methods without providing their actual implementation. Interfaces serve as a contract that implementing classes must adhere to, ensuring consistency across different classes that implement the same interface.

Multiple Interfaces Implementation:

  • A class can implement multiple interfaces by separating them with a comma.

Example:

interface Engine {
    void startEngine();
}

interface Horn {
    void honk();
}

class Truck implements Engine, Horn {
    @Override
    public void startEngine() {
        System.out.println("Truck engine started.");
    }

    @Override
    public void honk() {
        System.out.println("Truck is honking.");
    }
}

public class MultiInterfaceDemo {
    public static void main(String[] args) {
        Truck truck = new Truck();
        truck.startEngine();
        truck.honk();
    }
}
/*
Truck engine started.  
Truck is honking.
*/

interfaces can extend other interfaces, similar to how classes inherit from other classes. This allows for the creation of more specific interfaces based on broader ones, promoting a modular and hierarchical structure in application design. Unlike classes, interfaces can extend multiple interfaces, enabling the implementation of multiple behaviors in a single interface.

Syntax of Interface Extension

interface ParentInterface {
    void parentMethod();
}

interface ChildInterface extends ParentInterface {
    void childMethod();
}

Multiple Inheritance with Interfaces

Java does not allow multiple inheritance with classes, but interfaces can extend multiple interfaces.

The syntax is:

interface A {
    void methodA();
}

interface B {
    void methodB();
}

interface C extends A, B {
    void methodC();
}
//Now, any class implementing C must implement methods from both A and BCode language: PHP (php)

Example Program

// Parent Interface 1
interface Person {
    void showDetails();
}

// Parent Interface 2
interface Employee {
    void work();
}

// Child Interface extending multiple interfaces
interface Manager extends Person, Employee {
    void manage();
}

// Implementation class
class SoftwareManager implements Manager {
    @Override
    public void showDetails() {
        System.out.println("Name: Mahesh");
        System.out.println("Designation: Software Manager");
    }

    @Override
    public void work() {
        System.out.println("Managing software projects.");
    }

    @Override
    public void manage() {
        System.out.println("Managing team and resources.");
    }
}

public class MultipleInheritanceDemo {
    public static void main(String[] args) {
        SoftwareManager manager = new SoftwareManager();
        manager.showDetails();
        manager.work();
        manager.manage();
    }
}
/*
Name: Mahesh  
Designation: Software Manager  
Managing software projects.  
Managing team and resources.
*/

Multiple Inheritance by Implementing Multiple Interfaces in Java

A class can implement multiple interfaces, achieving multiple inheritance. Here is a detailed example demonstrating multiple inheritance by implementing multiple interfaces.

Program: Multiple Inheritance by Implementing Multiple Interfaces
// Parent Interface 1
interface Developer {
    void writeCode();
}

// Parent Interface 2
interface Tester {
    void testCode();
}

// Implementation class implementing both interfaces
class SoftwareEngineer implements Developer, Tester {
    @Override
    public void writeCode() {
        System.out.println("Writing efficient code.");
    }

    @Override
    public void testCode() {
        System.out.println("Testing code for bugs.");
    }
}

public class MultipleInheritanceDemo {
    public static void main(String[] args) {
        SoftwareEngineer engineer = new SoftwareEngineer();
        engineer.writeCode();
        engineer.testCode();
    }
}
/*
Writing efficient code.  
Testing code for bugs.
*/

Default and Static Methods in Interfaces (Java 8)

Before Java 8, interfaces could only declare abstract methods.

In Java 8 and later versions, interfaces can contain default and static methods. Here’s a simple explanation and a Java program demonstrating how to use both default and static methods in interfaces.

  • Default methods: These are methods that have a body in the interface itself. Default methods are introduced to allow developers to add new methods to interfaces without breaking the existing implementations of that interface.

  • Static methods: These are methods that belong to the interface itself, rather than to any instance of the interface. Static methods can be called using the interface name, not the object.

Default Methods:

These methods have a body and can be overridden by implementing classes. They enable backward compatibility without forcing all implementing classes to define new methods.

interface Vehicle {
    default void start() {
        System.out.println("Vehicle is starting...");
    }
}Code language: PHP (php)

Static Methods

These methods belong to the interface itself and are not inherited by implementing classes.

interface Calculator {
    static int add(int a, int b) {
        return a + b;
    }
}Code language: PHP (php)

Program

// Interface with default and static methods
interface Employee {
    // Default method with a body
    default void work() {
        System.out.println("Working from the office.");
    }

    // Static method
    static void takeBreak() {
        System.out.println("Taking a break.");
    }
}

// Class that implements the Employee interface
class Manager implements Employee {
    // Overriding the default method
    @Override
    public void work() {
        System.out.println("Managing the team and projects.");
    }
}

public class DefaultStaticMethodDemo {
    public static void main(String[] args) {
        // Create a Manager object
        Manager manager = new Manager();
        // Calling the overridden work method from Manager class
        manager.work();

        // Calling the default method from Employee interface
        Employee emp = new Manager();
        emp.work();  // Calls the work method from Manager class (overridden)

        // Calling the static method using the interface name
        Employee.takeBreak();  // Static method call
    }
}
/*
Managing the team and projects.
Managing the team and projects.
Taking a break.
*/

Private Methods in Interfaces (Java 9)

Java 9 further enhanced interfaces by allowing private methods. These methods can only be accessed within the interface and are useful for sharing common functionality among default methods.

interface Printer {
    default void printBlackAndWhite() {
        log("Printing in black and white...");
    }

    default void printColor() {
        log("Printing in color...");
    }

    private void log(String message) {
        System.out.println(message);
    }
}

class LaserPrinter implements Printer {}

public class PrivateMethodDemo {
    public static void main(String[] args) {
        LaserPrinter printer = new LaserPrinter();
        printer.printBlackAndWhite();
        printer.printColor();
    }
}
/*
Printing in black and white...  
Printing in color...
*/

Marker Interface:

  • An interface with no methods is known as a Marker Interface.

  • Example: Serializable, Cloneable.

import java.io.Serializable;

class Data implements Serializable {
    private int id;
    private String name;

    Data(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class MarkerInterfaceDemo {
    public static void main(String[] args) {
        Data data = new Data(1, "Java");
        System.out.println("Data object created.");
    }
}

Functional Interfaces (Java 8):

  • An interface with exactly one abstract method is called a Functional Interface.

  • Annotated with @FunctionalInterface.

  • Example: Runnable, Callable, Comparator.

@FunctionalInterface
interface Greet {
    void sayHello();
}

public class FunctionalInterfaceDemo {
    public static void main(String[] args) {
        Greet greet = () -> System.out.println("Hello, World!");
        greet.sayHello();
    }
}
/*
Hello, World!
*/

A complete Example Program

// Interface with constants, default, and static methods
interface Employee {
    // Constant in the interface
    int MAX_WORK_HOURS = 40;  // Implicitly static and final

    // Default method with a body
    default void work() {
        System.out.println("Working from the office for " + MAX_WORK_HOURS + " hours a week.");
    }

    // Static method in the interface
    static void takeBreak() {
        System.out.println("Taking a 15-minute break.");
    }

    // Abstract method to be implemented by classes
    void performDuties();
}

// Sub-interface that extends Employee
interface Manager extends Employee {
    // Overriding the default method
    @Override
    default void work() {
        System.out.println("Managing teams and projects for " + MAX_WORK_HOURS + " hours a week.");
    }

    // Implementing the abstract method from Employee
    @Override
    void performDuties();
}

// Concrete class implementing the Manager interface
class TeamManager implements Manager {
    // Providing implementation for the performDuties method
    @Override
    public void performDuties() {
        System.out.println("Handling the day-to-day tasks of team management.");
    }
}

public class InterfaceDemo {
    public static void main(String[] args) {
        // Create an object of TeamManager
        TeamManager manager = new TeamManager();

        // Calling the overridden work method from Manager interface
        manager.work();

        // Calling the performDuties method from TeamManager class
        manager.performDuties();

        // Calling the static method from Employee interface
        Employee.takeBreak();

        // Displaying the interface constant value
        System.out.println("Maximum working hours: " + Employee.MAX_WORK_HOURS);
    }
}
/*
Managing teams and projects for 40 hours a week.
Handling the day-to-day tasks of team management.
Taking a 15-minute break.
Maximum working hours: 40
*/

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top