Interface

What is an Interface?

Java interfaces are one of the core concepts of Java programming, providing a mechanism for defining a contract that classes must adhere to. A Java Interface is a reference type in Java, similar to a class, but it is a collection of abstract methods (methods without implementations) and constants. An interface provides a way to define a contract that classes can implement, meaning that any class that implements an interface must provide concrete implementations for the methods defined in the interface.

public interface InterfaceName {
    // abstract method
    void someMethod();

    // default method
    default void defaultMethod() {
        System.out.println("Default implementation");
    }

    // static method
    static void staticMethod() {
        System.out.println("Static method");
    }
}

Purpose of Interfaces

The primary purpose of interfaces is to define a contract that classes can implement. A class that implements an interface must provide concrete implementations for all the abstract methods declared in the interface (unless the class is abstract).

Interfaces enable:

  • Abstraction: By separating the definition of a method from its implementation, interfaces allow different implementations of the same functionality.

  • Multiple Inheritance: While Java doesn't allow multiple inheritance with classes, a class can implement multiple interfaces. This allows a class to inherit different behaviors from multiple sources.

  • Loose Coupling: Interfaces help in decoupling code. The client code doesn’t need to know the details of the class implementing the interface, only the interface itself.

Abstract Methods

By default, all methods declared in an interface are abstract (i.e., they do not have a body). Any class implementing the interface must provide a concrete implementation of these methods.

Default Methods

Introduced in Java 8, default methods allow interfaces to provide method implementations. This feature was introduced to ensure backward compatibility when new methods are added to interfaces.

How do default methods in interfaces work, and why were they introduced?

  • Mechanics of Default Methods: Default methods are regular methods with a body in an interface, marked with the default keyword. They allow interfaces to provide a standard implementation for a method, which implementing classes can either use as-is or override.

  • Purpose of Introduction: Default methods were introduced in Java 8 to ensure backward compatibility, especially in cases like the Java Collections API. Adding new methods (e.g., forEach) to interfaces without breaking existing code was made possible by default methods.

  • Avoiding Code Duplication: Default methods also help avoid code duplication by allowing common functionality across multiple classes to be defined directly within the interface.

Static Methods

Interfaces can define static methods that are independent of any instance. These methods are called using the interface name.

Constants

All fields declared in an interface are implicitly public, static, and final. They are treated as constants.

Private Methods

Since Java 9, interfaces can have private methods. These are used to share common code between default methods.

Access Modifiers

All methods in an interface are implicitly public and abstract (unless they are default or static). Private methods were introduced in Java 9 for use inside the interface only. Protected and default (package-private) methods are not allowed in interfaces and will cause compilation error.

Interface Inheritance

Interfaces can extend other interfaces. This means one interface can inherit the abstract methods of another interface. A class implementing the extended interface must implement all methods from both the parent and the child interfaces.

How would we handle method conflicts when a class implements multiple interfaces with the same method signature?

If two interfaces define the same method signature without a default implementation, there’s no conflict; the implementing class must simply provide its own implementation of the method.

If both interfaces have a default implementation for the same method, the implementing class must override the method to resolve the conflict. This is done by explicitly calling the desired interface’s method using InterfaceName.super.methodName() syntax within the overridden method, allowing you to specify which default method to use.

Nested Interface

A nested interface is an interface declared inside another interface or class. It is useful when we want to logically group interfaces together or restrict their scope to a particular enclosing class. They must be implemented by another class just like a normal interface.

Types of Nested Interfaces

1. Interface inside another Interface

When an interface is declared inside another interface, it is implicitly public and static. The nested interface can be accessed using OuterInterface.InnerInterface.

2. Interface inside a Class

When an interface is declared inside a class, it can have any access modifier (public, private, protected, or default). It is used when the interface should only be used within that class.

Interface in Design Patterns

Interface are often foundational in design patterns, particularly in cases like the Strategy Pattern, Observer Pattern, and Decorator Pattern.

Strategy Pattern

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern lets the algorithm vary independently from clients that use it. Interfaces are often used here to define a "strategy" interface that various concrete implementations (strategies) can adhere to.

Example:

Imagine a context where we have different payment methods (e.g., CreditCardPayment and PayPalPayment) that follow the same PaymentStrategy interface.

Observer Pattern

The Observer Pattern defines a one-to-many dependency between objects, so when one object changes state, all its dependents are notified and updated automatically. Interfaces allow defining the Observer interface that can be implemented by different types of observers.

Example:

Consider a WeatherStation that notifies various Observer objects (like a MobileDevice and WebApp) whenever weather data changes.

Decorator Pattern

The Decorator Pattern allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class. The Component interface allows for interchangeable decorations.

Example:

Consider a scenario where we have a Coffee interface, and different coffee types can have additional options like Milk or Sugar.

How does the JVM handle interfaces internally, and how does it resolve method calls for default and static methods?

  • Interface Table (ITable): When a class implements an interface, the JVM creates an interface table (ITable) that links methods declared in the interface to the actual implementation in the class. This enables polymorphic behavior.

  • Default Method Resolution: When a default method is invoked, the JVM first checks if the class overrides the method. If not, it checks the ITable to resolve the default method in the interface. If multiple interfaces contain conflicting default methods, the JVM throws an error unless the implementing class resolves the conflict by overriding the method.

  • Static Methods: Static methods in interfaces are resolved based on the interface name, as they belong to the interface itself and cannot be called on instances of implementing classes. The JVM doesn’t look for static methods in the ITable; it simply invokes them directly on the interface.

Last updated