Java Interface

What is an Interface in Java?

An interface in Java is a blueprint of a class. It is a collection of abstract methods and constants that specify the behavior that a class must implement. Unlike a class, an interface does not contain constructors and cannot have instance variables. Interfaces are primarily used to achieve abstraction and multiple inheritance in Java.

In simple terms, an interface defines what a class should do, but not how it should do it.

Key Features of Interfaces

  1. Achieves Complete Abstraction: Interfaces provide 100% abstraction by allowing only method declarations (before Java 8).
  2. Multiple Inheritance Support: A class can implement multiple interfaces, overcoming the limitation of single inheritance in Java classes.
  3. Method Declarations: Methods in an interface are abstract by default, which means they have no body.
  4. Constants Only: Variables declared in an interface are public, static and final by default.
  5. Default and Static Methods: Since Java 8, interfaces can also have default and static methods with a body.
  6. Functional Interfaces: Introduced in Java 8, a functional interface has only one abstract method. These are commonly used in lambda expressions.

Syntax of an Interface

interface InterfaceName {
// Abstract method
void method1();

// Default method
default void method2() {
System.out.println("This is a default method");
}

// Static method
static void method3() {
System.out.println("This is a static method");
}

// Constant
int CONSTANT_VALUE = 100; // public static final by default
}

How to Implement an Interface

A class must use the implements keyword to define the behavior of the methods declared in an interface.

Example of Interface Implementation

interface Animal {
void sound(); // Abstract method
void eat(); // Abstract method
}

class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}

@Override
public void eat() {
System.out.println("Dog eats bones");
}
}

public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
myDog.eat();
}
}

Output:

Dog barks
Dog eats bones

Interface vs. Abstract Class

FeatureInterfaceAbstract Class
Abstraction LevelAchieves 100% abstractionPartial abstraction
MethodsOnly abstract (default), default, and staticAbstract and concrete methods
Variablespublic static final by defaultCan have instance variables
InheritanceSupports multiple inheritanceSupports single inheritance
ConstructorCannot have constructorsCan have constructors
Access ModifiersMethods are public by defaultCan have any access modifier

Default and Static Methods in Interfaces

Since Java 8, interfaces can have:

  1. Default Methods: These are methods with a body and are marked with the default keyword. They allow backward compatibility without breaking existing implementations.
  2. Static Methods: These methods belong to the interface itself and cannot be overridden by implementing classes.

Example: Default and Static Methods

interface Vehicle {
void start();

default void honk() {
System.out.println("Honking...");
}

static void service() {
System.out.println("Vehicle service is due");
}
}

class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car starts");
}
}

public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start();
myCar.honk();
Vehicle.service(); // Static method called using interface name
}
}

Output:

Car starts
Honking...
Vehicle service is due

Functional Interfaces

A functional interface is an interface that has exactly one abstract method. Functional interfaces are used extensively with lambda expressions in Java 8 and later.

Example: Functional Interface

@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}

public class Main {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;

System.out.println("Sum: " + add.calculate(5, 3));
System.out.println("Product: " + multiply.calculate(5, 3));
}
}

Output:

Sum: 8
Product: 15

Advantages of Using Interfaces

  1. Supports Multiple Inheritance: Allows a class to implement multiple interfaces, overcoming single inheritance limitations.
  2. Encourages Polymorphism: Classes can implement interfaces to achieve runtime polymorphism.
  3. Promotes Loose Coupling: Interfaces define contracts that decouple implementation from usage.
  4. Enables Testability: Interfaces can be easily mocked for testing purposes.

Leave a Comment