Java Interface

Discover how interfaces provide 100% abstraction, enable multiple inheritance, and create powerful, flexible applications with clean contracts between classes.

What is an Interface?

An interface in Java is a blueprint of a class that contains only abstract methods and constants. It's used to achieve 100% abstraction and multiple inheritance in Java. Think of an interface as a contract that classes must follow – it defines "what" must be done, but not "how" to do it.

Imagine a TV remote control interface – it has buttons for power, volume, and channels. Different TV brands (Sony, Samsung, LG) all implement these buttons, but each brand does it differently internally. The interface (remote layout) is the same, but the implementation varies!

  • 100% Abstraction: All methods are abstract by default (before Java 8)
  • Multiple Inheritance: A class can implement multiple interfaces
  • Contract: Ensures classes implement specific methods

Real-Life Analogy: A USB port is an interface – it defines how devices connect. Your keyboard, mouse, printer, and phone charger all use the USB interface, but each device works differently inside. That's the power of interfaces!

Interface Syntax

Interfaces are declared using the interface keyword, and classes implement them using the implements keyword.

Syntax: Declaring and Implementing Interface

// Declaring an interface
interface InterfaceName {
    // Abstract method (no body)
    void method1();
    void method2();
    
    // Constants (public, static, final by default)
    int CONSTANT = 100;
}

// Implementing an interface
class ClassName implements InterfaceName {
    // Must provide implementation for all interface methods
    public void method1() {
        // Implementation
    }
    
    public void method2() {
        // Implementation
    }
}

Key Points:

  • Use interface keyword to declare an interface
  • Use implements keyword for a class to implement an interface
  • All methods in interface are public abstract by default
  • All variables in interface are public static final by default

Simple Interface Example

Let's create a basic Animal interface and implement it in different classes.

Example: Basic Interface Implementation

// Interface
interface Animal {
    // Abstract methods (public abstract by default)
    void eat();
    void sound();
}

// Class implementing the interface
class Dog implements Animal {
    // Must implement all interface methods
    public void eat() {
        System.out.println("Dog eats bones and meat");
    }
    
    public void sound() {
        System.out.println("Dog barks: Woof! Woof!");
    }
}

class Cat implements Animal {
    public void eat() {
        System.out.println("Cat eats fish and milk");
    }
    
    public void sound() {
        System.out.println("Cat meows: Meow! Meow!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.eat();
        dog.sound();
        
        System.out.println();
        
        Animal cat = new Cat();
        cat.eat();
        cat.sound();
    }
}
Output:
Dog eats bones and meat
Dog barks: Woof! Woof!

Cat eats fish and milk
Cat meows: Meow! Meow!

Explanation:

  • Animal is an interface with two abstract methods
  • Both Dog and Cat classes implement the Animal interface
  • Each class must provide implementation for all interface methods
  • Interface reference (Animal) can point to any implementing class object

Multiple Interface Implementation

Unlike classes, Java allows a class to implement multiple interfaces, solving the multiple inheritance problem!

Example: Multiple Inheritance Using Interfaces

// First Interface
interface Printable {
    void print();
}

// Second Interface
interface Showable {
    void show();
}

// Class implementing multiple interfaces
class Document implements Printable, Showable {
    public void print() {
        System.out.println("Printing document...");
    }
    
    public void show() {
        System.out.println("Showing document on screen...");
    }
}

public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        doc.print();
        doc.show();
    }
}
Output:
Printing document...
Showing document on screen...

Explanation:

  • Document class implements both Printable and Showable interfaces
  • Use comma to separate multiple interfaces: implements Interface1, Interface2
  • Class must implement methods from all interfaces
  • This is how Java achieves multiple inheritance safely!

Interface with Constants

Interfaces can have constants that are automatically public, static, and final.

Example: Interface Constants

interface Bank {
    // Constants (automatically public static final)
    double INTEREST_RATE = 7.5;
    int MIN_BALANCE = 1000;
    
    // Abstract methods
    void deposit(double amount);
    void withdraw(double amount);
}

class SavingsAccount implements Bank {
    double balance;
    
    SavingsAccount(double initialBalance) {
        this.balance = initialBalance;
    }
    
    public void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited: $" + amount);
        System.out.println("New Balance: $" + balance);
    }
    
    public void withdraw(double amount) {
        if (balance - amount >= MIN_BALANCE) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
            System.out.println("New Balance: $" + balance);
        } else {
            System.out.println("Insufficient balance! Minimum balance required: $" + MIN_BALANCE);
        }
    }
    
    void displayInterestRate() {
        System.out.println("Interest Rate: " + INTEREST_RATE + "%");
    }
}

public class Main {
    public static void main(String[] args) {
        SavingsAccount acc = new SavingsAccount(5000);
        acc.displayInterestRate();
        acc.deposit(2000);
        System.out.println();
        acc.withdraw(6500);
    }
}
Output:
Interest Rate: 7.5%
Deposited: $2000.0
New Balance: $7000.0

Insufficient balance! Minimum balance required: $1000

Explanation:

  • Interface constants are automatically public static final
  • Constants can be accessed using interface name or implementing class
  • These constants cannot be modified (they're final)
  • Perfect for defining configuration values shared across implementations

Real-World Example: Payment System

A practical example showing how interfaces create flexible payment processing systems.

Example: Payment Interface

interface Payment {
    void processPayment(double amount);
    void generateReceipt();
}

class CreditCardPayment implements Payment {
    String cardNumber;
    
    CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }
    
    public void processPayment(double amount) {
        System.out.println("Processing Credit Card payment of $" + amount);
        System.out.println("Card: ****" + cardNumber.substring(cardNumber.length() - 4));
    }
    
    public void generateReceipt() {
        System.out.println("Credit Card receipt generated");
    }
}

class PayPalPayment implements Payment {
    String email;
    
    PayPalPayment(String email) {
        this.email = email;
    }
    
    public void processPayment(double amount) {
        System.out.println("Processing PayPal payment of $" + amount);
        System.out.println("Email: " + email);
    }
    
    public void generateReceipt() {
        System.out.println("PayPal receipt sent to email");
    }
}

class CashPayment implements Payment {
    public void processPayment(double amount) {
        System.out.println("Processing Cash payment of $" + amount);
        System.out.println("Payment received in cash");
    }
    
    public void generateReceipt() {
        System.out.println("Cash receipt printed");
    }
}

public class Main {
    public static void main(String[] args) {
        Payment payment1 = new CreditCardPayment("1234567890123456");
        payment1.processPayment(500);
        payment1.generateReceipt();
        
        System.out.println("\n" + "-".repeat(40) + "\n");
        
        Payment payment2 = new PayPalPayment("user@example.com");
        payment2.processPayment(300);
        payment2.generateReceipt();
        
        System.out.println("\n" + "-".repeat(40) + "\n");
        
        Payment payment3 = new CashPayment();
        payment3.processPayment(200);
        payment3.generateReceipt();
    }
}
Output:
Processing Credit Card payment of $500.0
Card: ****3456
Credit Card receipt generated

----------------------------------------

Processing PayPal payment of $300.0
Email: user@example.com
PayPal receipt sent to email

----------------------------------------

Processing Cash payment of $200.0
Payment received in cash
Cash receipt printed

Explanation:

  • Payment interface defines a common contract for all payment methods
  • Each payment type implements the interface differently
  • Easy to add new payment methods without changing existing code
  • Interface reference works with any implementing class – perfect polymorphism!

Interface Inheritance

Interfaces can extend other interfaces, creating a hierarchy of contracts.

Example: Interface Extending Interface

// Parent interface
interface Vehicle {
    void start();
    void stop();
}

// Child interface extending parent
interface FourWheeler extends Vehicle {
    void changeGear();
}

// Class implementing child interface must implement all methods
class Car implements FourWheeler {
    public void start() {
        System.out.println("Car is starting...");
    }
    
    public void stop() {
        System.out.println("Car is stopping...");
    }
    
    public void changeGear() {
        System.out.println("Changing gear in car...");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.start();
        myCar.changeGear();
        myCar.stop();
    }
}
Output:
Car is starting...
Changing gear in car...
Car is stopping...

Explanation:

  • FourWheeler interface extends Vehicle interface using extends keyword
  • Car must implement methods from both FourWheeler and Vehicle
  • Interfaces use extends for inheritance, not implements
  • An interface can extend multiple interfaces: interface C extends A, B

Interface Features in Java 8+

1. Default Methods (Java 8)

Default methods have implementation in interfaces. They use the default keyword and provide backward compatibility when adding new methods to existing interfaces.

Example: default void log() { System.out.println("Logging..."); }

2. Static Methods (Java 8)

Static methods in interfaces belong to the interface itself, not to implementing classes. They provide utility functions related to the interface.

Example: static void printInfo() { System.out.println("Interface info"); }

3. Private Methods (Java 9)

Private methods help reduce code duplication within default methods. They cannot be accessed outside the interface.

Example: private void helper() { /* common code */ }

Default and Static Methods Example

Java 8 introduced default and static methods to make interfaces more powerful and flexible.

Example: Default and Static Methods

interface MyInterface {
    // Abstract method
    void abstractMethod();
    
    // Default method (has body)
    default void defaultMethod() {
        System.out.println("This is a default method");
    }
    
    // Static method (has body)
    static void staticMethod() {
        System.out.println("This is a static method");
    }
}

class MyClass implements MyInterface {
    // Must implement abstract method
    public void abstractMethod() {
        System.out.println("Implementing abstract method");
    }
    
    // Can optionally override default method
    // Not required!
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        
        obj.abstractMethod();      // From implementation
        obj.defaultMethod();       // From interface (default)
        
        // Static method called using interface name
        MyInterface.staticMethod();
    }
}
Output:
Implementing abstract method
This is a default method
This is a static method

Explanation:

  • Default methods provide implementation in interface, implementing classes inherit it
  • Classes can override default methods if needed
  • Static methods are called using interface name, not through objects
  • These features add flexibility while maintaining backward compatibility

Abstract Class vs Interface

  • Abstract Class: Can have both abstract and concrete methods, supports constructors, can have instance variables, use extends keyword, only single inheritance
  • Interface: All methods abstract by default (except default/static in Java 8+), no constructors, only constants (public static final), use implements keyword, supports multiple inheritance
  • When to Use Abstract Class: When classes share common code and have "is-a" relationship
  • When to Use Interface: When you want to define a contract, achieve multiple inheritance, or work with unrelated classes

Quick Rule: Use interfaces for "can-do" relationships (Bird can fly, Fish can swim) and abstract classes for "is-a" relationships (Dog is an Animal). A class can implement multiple interfaces but extend only one class!

Combining Interface and Inheritance

A powerful example showing how classes can extend another class while implementing multiple interfaces.

Example: Extends and Implements Together

// Parent class
class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}

// Interfaces
interface Swimmable {
    void swim();
}

interface Flyable {
    void fly();
}

// Duck extends Animal and implements both interfaces
class Duck extends Animal implements Swimmable, Flyable {
    public void swim() {
        System.out.println("Duck is swimming in water");
    }
    
    public void fly() {
        System.out.println("Duck is flying in the sky");
    }
}

public class Main {
    public static void main(String[] args) {
        Duck duck = new Duck();
        
        duck.eat();   // From Animal class
        duck.swim();  // From Swimmable interface
        duck.fly();   // From Flyable interface
    }
}
Output:
This animal eats food
Duck is swimming in water
Duck is flying in the sky

Explanation:

  • Duck extends Animal class (single inheritance)
  • Duck implements both Swimmable and Flyable interfaces (multiple inheritance)
  • Syntax: class Duck extends Animal implements Swimmable, Flyable
  • This demonstrates the power of combining inheritance and interfaces!

Key Rules for Interfaces

  • Cannot Be Instantiated: You cannot create objects of an interface
  • All Methods Public: Interface methods are public by default (you can skip writing public)
  • All Variables Constants: Variables are automatically public static final
  • Multiple Implementation: A class can implement multiple interfaces
  • Interface Extends Interface: Use extends keyword, not implements
  • Must Implement All Methods: Implementing class must provide body for all abstract methods

Common Mistake: Forgetting to implement all interface methods or using wrong access modifier (methods must be public in implementing class) will cause compilation errors!

Advantages of Interfaces

  • 100% Abstraction: Achieve complete abstraction of functionality
  • Multiple Inheritance: Java's solution to multiple inheritance problem
  • Loose Coupling: Reduce dependencies between components
  • Flexibility: Easy to switch implementations without changing client code
  • Testability: Easy to create mock implementations for testing
  • Standard Contract: Ensures all implementations follow same contract

Design Principle: "Program to an interface, not an implementation." This makes your code more flexible, maintainable, and easier to test. It's a fundamental principle of good software design!

Real-World Use Cases

  • Database Connectivity: JDBC uses interfaces like Connection, Statement, ResultSet
  • Collections Framework: List, Set, Map are all interfaces with multiple implementations
  • Event Handling: ActionListener, MouseListener interfaces in GUI programming
  • Web Services: Define API contracts using interfaces
  • Plugin Architecture: Allow third-party extensions through interfaces
  • Dependency Injection: Framework-independent code using interface contracts

Industry Example: Java's List interface has multiple implementations: ArrayList (fast random access), LinkedList (fast insertions), Vector (thread-safe). You can switch between them without changing your code – that's the power of programming to interfaces!

Key Points to Remember

  • Interfaces define "what" to do, not "how" to do it
  • Use interface keyword to declare, implements to use
  • All methods are public abstract by default (before Java 8)
  • All variables are public static final by default
  • A class can implement multiple interfaces (multiple inheritance)
  • Cannot create objects of interfaces, but can use them as reference types
  • Java 8+ added default and static methods to interfaces
  • Interfaces can extend other interfaces using extends

Final Thought: Think of interfaces as contracts or blueprints. They define capabilities without dictating implementation. This makes your code flexible, extensible, and follows the open-closed principle: open for extension, closed for modification!