🔌 Interfaces
A reference type in Java that can contain abstract methods, default methods, and static constants. Used to achieve full abstraction and multiple inheritance.
1. What is an Interface?
An interface is a blueprint of a class. It is a completely "abstract class" that is used to group related methods with empty bodies. It serves as a contract—any class that implements an interface must fulfill the contract by providing implementations for all its abstract methods.
You define an interface using the interface keyword. Historically (before Java 8), interfaces represented pure abstraction because they could only contain abstract methods and constant fields.
2. Syntax & Implicit Modifiers
Interfaces have strict rules about their members:
- All methods are implicitly public abstract. You do not need to type these modifiers.
- All fields are implicitly public static final (constants). You must initialize them.
- You cannot instantiate an interface directly using new.
3. Implementing Multiple Interfaces
Java classes do not support multiple inheritance of state (extending more than one class) to avoid the "Diamond Problem". However, a class can implement multiple interfaces, separating them with a comma. This is Java's workaround for multiple inheritance of type.
interface Flyable { int MAX_SPEED = 100; // public static final implicitly void fly(); // public abstract implicitly } interface Swimmable { void swim(); } // A class implementing multiple interfaces public class Duck implements Flyable, Swimmable { @Override public void fly() { System.out.println("Duck is flying at speed: " + MAX_SPEED); } @Override public void swim() { System.out.println("Duck is swimming in the pond."); } public static void main(String[] args) { Duck donald = new Duck(); donald.fly(); donald.swim(); } }
4. Interface vs Abstract Class
| Feature | Interface | Abstract Class |
|---|---|---|
| Inheritance | A class can implement multiple interfaces. | A class can extend only one abstract class. |
| Methods | Default, static, and abstract methods. No final methods. | Can have abstract and non-abstract methods of any access level. |
| Variables | Only public static final variables (constants). | Can have instance variables (non-final, non-static). |
| Constructors | Cannot have constructors. | Can have constructors (called during subclass creation). |
| Access Modifiers | Methods are implicitly public (private allowed since Java 9). | Can use any access modifier for methods and fields. |
| State | Cannot maintain state (no instance fields). | Can maintain state using instance variables. |
| When to use? | To define a contract or capability (e.g., Runnable, Comparable). | To share code among closely related classes (e.g., Animal). |
5. Default Methods (Java 8)
In Java 8, interfaces were allowed to have method bodies using the default keyword. This was primarily added for backward compatibility. It allowed the designers of Java to add new methods to existing interfaces (like Collection and List) without breaking all the classes worldwide that implement those interfaces.
interface Vehicle { void startEngine(); // Default method with a body default void honk() { System.out.println("Beep beep!"); } } class Car implements Vehicle { @Override public void startEngine() { System.out.println("Car engine started."); } } public class Main { public static void main(String[] args) { Car myCar = new Car(); myCar.startEngine(); myCar.honk(); // Inherited from interface } }
Diamond Problem Resolution
If a class implements two interfaces that provide a default method with the same signature, it causes a compile-time error. The class must override the method to resolve the conflict.
interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } public class C implements A, B { // Must override to resolve conflict @Override public void show() { A.super.show(); // Calling interface A's default method System.out.println("C's own implementation"); } }
6. Static & Private Methods
Static Methods (Java 8): Interfaces can have static methods. They belong to the interface class itself, not instances, and are used for utility or helper methods.
Private Methods (Java 9): Interfaces can have private methods (and private static methods) to share common code between default methods without exposing that code to implementing classes.
7. Functional Interfaces
A Functional Interface is an interface that contains exactly one abstract method. They can have any number of default or static methods. These are critical in Java 8+ because they are used as the basis for Lambda Expressions.
The @FunctionalInterface annotation is optional but recommended. It tells the compiler to enforce the single abstract method rule.
@FunctionalInterface interface MathOperation { int operate(int a, int b); // Exactly one abstract method } public class FunctionalInterfaceDemo { public static void main(String[] args) { // Using lambda expression MathOperation add = (a, b) -> a + b; MathOperation multiply = (a, b) -> a * b; System.out.println("Add: " + add.operate(5, 3)); System.out.println("Multiply: " + multiply.operate(5, 3)); } }
8. Marker Interfaces
A Marker Interface is an empty interface (no methods or fields). It is used to signal to the JVM or a framework that a class has some special property.
java.io.Serializable: Marks a class as capable of being serialized (converted to a byte stream).java.lang.Cloneable: Marks a class as supporting theObject.clone()method.