In this Java tutorial, you will learn what interfaces in Java are, how a class implements an interface, how interface methods are enforced by the compiler, and where default methods, static methods, constants, and functional interfaces fit in.

What Interfaces in Java Mean

An interface in Java defines a contract that implementing classes must follow. It can declare method names, return types, parameters, constants, and some supported method implementations. A class that implements an interface agrees to provide the behavior required by that interface.

Interfaces have a similar structure as that of a class, but they are mainly used to define capabilities. In older Java usage, an interface was usually explained as a type with abstract methods and constants. In modern Java, an interface can also contain default methods, static methods, and private helper methods, but its main purpose is still to define a common contract.

If a class is implementing an interface, this means that class is promising that the abstract methods in the interface shall be implemented. Compiler makes sure that this promise is not broken. If this promise is broken, in cases like any of the methods is not implemented, compiler throws an error during compilation and stops.

For an example from Java language itself, FileInputStream class implements Closeable interface. And FileInputStream implements the method close(), which is enforced by Closeable interface.

Java Interface Syntax for Methods and Constants

The basic syntax of a Java interface uses the interface keyword. A class uses the implements keyword to implement an interface.

</>
Copy
interface InterfaceName {
    // public static final by default
    int CONSTANT_VALUE = 10;

    // public abstract by default
    void methodName();
}

class ClassName implements InterfaceName {
    @Override
    public void methodName() {
        // method implementation
    }
}

In an interface, fields are implicitly public static final. Abstract methods are implicitly public abstract. When a class implements the interface, the implemented methods must be declared public, because the class cannot reduce the visibility of an interface method.

Interfaces in Java Example with Car and Jaguar

In the following program, InterfaceDemo.java, we shall look create an interface called Car, and a class called Jaguar. The Car interface has methods accelerate and break. Jaguar implements Car interface and so Jaguar should implement the methods accelerate and break enforced by the Car interface.

Car.java

</>
Copy
public interface Car {
	public void accelerate();
	public void breaking();
}

Jaguar.java

</>
Copy
public class Jaguar implements Car {

	String name;
	
	public Jaguar(String name){
		this.name = name;
	}
	
	@Override
	public void accelerate() {
		System.out.println(name + " is accelerating.");
	}

	@Override
	public void breaking() {
		System.out.println(name + " is breaking.");
	}
}

InterfaceDemo.java

</>
Copy
/**
 * Example program to show the working of an interface in Java
 * @author tutorialkart.com
 *
 */
public class InterfaceDemo {

	public static void main(String[] args) {
		System.out.println("---Demo on Interfaces in Java---");
		Jaguar myNewJaguar = new Jaguar("XJ");
		myNewJaguar.accelerate();
		myNewJaguar.breaking();
	}

}

Output

---Demo on Interfaces in Java---
XJ is accelerating.
XJ is breaking.

In this example, Car describes what a car-like object must do. Jaguar provides the actual implementation for accelerate() and breaking(). The compiler checks this at compile time.

Using a Java Interface as a Type

An interface can also be used as a reference type. This is one of the main reasons interfaces are useful. Code can depend on the interface instead of depending on one specific implementation class.

</>
Copy
interface PaymentService {
    void pay(double amount);
}

class CardPayment implements PaymentService {
    @Override
    public void pay(double amount) {
        System.out.println("Paid " + amount + " using card.");
    }
}

class UpiPayment implements PaymentService {
    @Override
    public void pay(double amount) {
        System.out.println("Paid " + amount + " using UPI.");
    }
}

public class PaymentDemo {
    public static void main(String[] args) {
        PaymentService payment = new CardPayment();
        payment.pay(500.0);

        payment = new UpiPayment();
        payment.pay(250.0);
    }
}

Output

Paid 500.0 using card.
Paid 250.0 using UPI.

Here, the variable payment is of type PaymentService. It can refer to any object whose class implements PaymentService. This helps write flexible code, because the calling code does not need to know the exact class behind the interface reference.

Implementing Multiple Interfaces in Java

A Java class can extend only one class, but it can implement multiple interfaces. This is useful when a class must support more than one capability.

</>
Copy
interface Printable {
    void print();
}

interface Scannable {
    void scan();
}

class MultiFunctionPrinter implements Printable, Scannable {
    @Override
    public void print() {
        System.out.println("Printing document.");
    }

    @Override
    public void scan() {
        System.out.println("Scanning document.");
    }
}

public class MultipleInterfacesDemo {
    public static void main(String[] args) {
        MultiFunctionPrinter printer = new MultiFunctionPrinter();
        printer.print();
        printer.scan();
    }
}

Output

Printing document.
Scanning document.

In this example, MultiFunctionPrinter implements both Printable and Scannable. Therefore, it must provide implementations for both print() and scan().

Default and Static Methods in Java Interfaces

Java interfaces can contain default methods and static methods. A default method has a method body and can be inherited by implementing classes. A static method belongs to the interface itself and is called using the interface name.

</>
Copy
interface Logger {
    void log(String message);

    default void logInfo(String message) {
        log("INFO: " + message);
    }

    static String formatError(String message) {
        return "ERROR: " + message;
    }
}

class ConsoleLogger implements Logger {
    @Override
    public void log(String message) {
        System.out.println(message);
    }
}

public class InterfaceMethodDemo {
    public static void main(String[] args) {
        Logger logger = new ConsoleLogger();
        logger.logInfo("Application started");

        System.out.println(Logger.formatError("Invalid input"));
    }
}

Output

INFO: Application started
ERROR: Invalid input

Default methods are useful when an interface needs a common behavior without forcing every implementing class to write the same code. Static interface methods are useful for helper behavior related to the interface.

Functional Interfaces in Java

A functional interface is an interface with exactly one abstract method. Functional interfaces are commonly used with lambda expressions. The @FunctionalInterface annotation is optional, but it asks the compiler to check that the interface has only one abstract method.

</>
Copy
@FunctionalInterface
interface Calculator {
    int operate(int a, int b);
}

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

        System.out.println(add.operate(10, 5));
        System.out.println(multiply.operate(10, 5));
    }
}

Output

15
50

Common built-in functional interfaces in Java include Predicate, Function, Consumer, and Supplier. These are widely used in lambda expressions and stream operations.

Interface and Abstract Class Difference in Java

Interfaces and abstract classes can both define abstract methods, but they are used for different design needs. An interface defines a capability or contract. An abstract class is usually used when related classes share common state and common base behavior.

FeatureJava InterfaceAbstract Class
Main purposeDefines a contract or capabilityProvides a shared base for related classes
Inheritance supportA class can implement multiple interfacesA class can extend only one abstract class
FieldsFields are constants by defaultCan have instance variables
ConstructorsCannot have constructorsCan have constructors
MethodsCan have abstract, default, static, and private methodsCan have abstract and concrete methods

Use an interface when different classes need to promise the same behavior. Use an abstract class when closely related classes need shared fields or common base implementation.

Common Mistakes with Interfaces in Java

  • Forgetting to implement all abstract methods: A non-abstract class must implement every abstract method declared by the interface.
  • Reducing method visibility: Interface methods are public, so the implementation method in the class must also be public.
  • Trying to create an object of an interface: An interface cannot be instantiated directly. It needs an implementing class or a lambda expression for a functional interface.
  • Using an interface when shared state is required: If classes need common instance variables and constructors, an abstract class may be a better fit.
  • Adding too many unrelated methods: A large interface can force classes to implement methods they do not need. Smaller focused interfaces are easier to maintain.

Java Interface Checklist for Code Review

  • Check that the interface name clearly describes a capability, such as Printable, Closeable, or PaymentService.
  • Check that implementing classes declare interface methods as public.
  • Check that the interface contains related methods instead of unrelated responsibilities.
  • Check whether a functional interface really has only one abstract method before using it with a lambda expression.
  • Check whether an interface is the right choice, or whether an abstract class is needed for shared state and constructors.

Interfaces in Java FAQs

What is an interface in Java with example?

An interface in Java is a contract that declares behavior for implementing classes. For example, a Car interface can declare accelerate() and breaking(), and a Jaguar class can implement those methods.

Can a Java class implement more than one interface?

Yes. A Java class can implement multiple interfaces by separating interface names with commas after the implements keyword. The class must implement the required abstract methods from all those interfaces.

What are the four common functional interfaces in Java?

Four commonly used built-in functional interfaces are Predicate, Function, Consumer, and Supplier. They are often used with lambda expressions and stream operations.

Can an interface in Java have method implementations?

Yes. Java interfaces can have default methods and static methods with method bodies. They can also have private helper methods in supported Java versions.

How is an interface related to abstraction in Java?

An interface supports abstraction by exposing what operations are available while hiding how each implementing class performs those operations. The implementation details remain inside the implementing class.

Key Takeaways for Interfaces in Java

In this Java Tutorial, we have learnt about Interfaces in Java that realize Abstraction in Java. A Java interface defines a contract, an implementing class provides the actual behavior, and the compiler ensures that required methods are implemented. Interfaces are also useful as types, for multiple capabilities, for default and static methods, and for functional programming with lambda expressions.