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.
Reference Type: In Java, both classes and interfaces are reference types. This means that they do not hold data directly (like primitive types do), but rather reference or point to objects in memory. When we declare a variable of a class or interface type, it can reference an object of that type.
MyClass obj = new MyClass(); // obj is a reference of type MyClass MyInterface obj2 = new MyClass(); // obj2 is a reference of type MyInterfaceKey Differences:
Classes define both the behavior (methods) and the structure (fields) of objects.
Interfaces define only method signatures (and constants), without any implementation. A class that implements an interface must provide the actual implementation for the abstract methods declared in the interface.
While an interface can define constants and abstract methods, it cannot define instance fields (variables that hold data). Additionally, interfaces can have default methods with implementations, starting from Java 8, and static methods. However, they still serve to provide a contract for what behaviors a class should implement, rather than dictating how those behaviors are implemented.
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.
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.
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.
public interface PublicInner- Can be accessed and implemented from anywhere.protected interface ProtectedInner- Can be accessed and implemented within the same package or subclasses.interface DefaultInner(Package-Private) - Can be accessed and implemented only within the same package.private interface PrivateInner- Cannot be directly implemented outsideOuterClass, so it's accessed through a method that returns an anonymous 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