What is a Java interface?

A Java interface is a reference type similar to a class but used to specify a contract for implementing classes. It contains method declarations (without implementations) that the implementing class must define. Interfaces help achieve abstraction and support multiple inheritance in Java, enabling developers to design modular and reusable code.

Let's consider a real-world scenario where multiple devices (like Printers, Scanners, and Fax Machines) are connected to a computer. Each device performs a specific function, but all follow a standard set of operations defined by an interface.

Let's move forward and see what's the syntax and examples of Java interface:

Syntax of Java interface

The syntax of a Java interface is straightforward. It uses the interface keyword and consists of method declarations without a body. Constants (static final fields) can also be declared.

// Syntax of an Interface
interface InterfaceName {
// Abstract method
void methodName();
// Constant
int CONSTANT_NAME = 100;
}

Now that we know the structure of an interface, let’s explore how it’s used in real-world applications.

Java interface example

Imagine an online shopping platform where users can choose their preferred payment methods at checkout. The system supports CreditCard and PayPal payments. Each payment method processes the transaction amount and generates a receipt with a unique transaction ID. For instance, a user paying $150.75 via CreditCard will see a receipt specific to their card, while another user opting for PayPal for $200.50 will receive a PayPal receipt. This approach ensures consistency in payment handling while allowing flexibility to add new payment methods in the future. Let's write a code for this scenario below:

// Define the Payment interface
interface Payment {
void processPayment(double amount);
void generateReceipt(String transactionId);
}
// Implementing the interface for Credit Card payments
class CreditCardPayment implements Payment {
public void processPayment(double amount) {
System.out.println("Processing Credit Card payment of $" + amount);
}
public void generateReceipt(String transactionId) {
System.out.println("Credit Card Receipt: Transaction ID - " + transactionId);
}
}
// Implementing the interface for PayPal payments
class PayPalPayment implements Payment {
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
public void generateReceipt(String transactionId) {
System.out.println("PayPal Receipt: Transaction ID - " + transactionId);
}
}
// Main class to execute the example
public class main {
public static void main(String[] args) {
// Using the Credit Card Payment method
Payment creditCard = new CreditCardPayment();
creditCard.processPayment(150.75);
creditCard.generateReceipt("CC12345");
System.out.println();
// Using the PayPal Payment method
Payment payPal = new PayPalPayment();
payPal.processPayment(200.50);
payPal.generateReceipt("PP67890");
}
}

Explanation

  • Line 2–5: The Payment interface defines two methods: processPayment and generateReceipt. These are abstract by default, meaning they don't have implementations.

  • Line 8–27: The CreditCardPayment and PayPalPayment classes implement the Payment interface. These classes provide their own specific logic for processing payments and generating receipts.

  • Line 30–44: In the Main class, the Payment interface is used to reference the objects of CreditCardPayment and PayPalPayment. This allows flexibility to use different payment methods interchangeably.

Difference between class and interface

Class

Interface

A blueprint to create objects with fields and methods.

A contract that specifies methods a class must implement.

It can contain implemented and abstract methods.

It contains only abstract methods (except default/static).

Class support single inheritance only.

Iterface supports multiple inheritance by implementing multiple interfaces.

It can have instance variables and constants.

It contains only static final constants.

What are multiple interfaces?

Java allows a class to implement multiple interfaces, which is a way to inherit behavior from multiple sources. An interface in Java is a contract that defines a set of methods without providing the implementation. When a class implements multiple interfaces, it inherits the methods from all those interfaces and must provide implementations for them.

Why do we need multiple interfaces?

  • Flexibility: A class can adopt features from multiple interfaces, making it highly flexible.

  • Avoids ambiguity: Since interfaces only provide method signatures, the class can implement the methods explicitly, avoiding any ambiguity.

  • Clean design: Instead of using multiple classes to inherit features, we can split different behaviors into multiple interfaces and have one class implement them all.

Example

Imagine a media player that supports multiple functions. It can play audio files, record audio, and stream videos. Instead of creating a huge class that does all of these things, we can split these behaviors into different interfaces.

  1. Playable interface: Contains a method to play media.

  2. Recordable interface: Contains a method to record media.

  3. Streamable interface: Contains a method to stream media.

Now, the MediaPlayer class can implement all three interfaces, providing implementations for each behavior.

Example code

// Interface for playing media
interface Playable {
void play();
}
// Interface for recording media
interface Recordable {
void record();
}
// Interface for streaming media
interface Streamable {
void stream();
}
// Class implementing all interfaces
class MediaPlayer implements Playable, Recordable, Streamable {
// Implementing play method from Playable interface
@Override
public void play() {
System.out.println("Playing media...");
}
// Implementing record method from Recordable interface
@Override
public void record() {
System.out.println("Recording media...");
}
// Implementing stream method from Streamable interface
@Override
public void stream() {
System.out.println("Streaming media...");
}
}
// Main class to test the MediaPlayer
public class main {
public static void main(String[] args) {
MediaPlayer player = new MediaPlayer();
player.play(); // Output: Playing media...
player.record(); // Output: Recording media...
player.stream(); // Output: Streaming media...
}
}

Explanation of the code

  • Lines 2–14: We have three interfaces, Playable, Recordable, and Streamable, each defining a single method.

  • Lines 17–36: The MediaPlayer class implements all three interfaces. It provides its own implementations for the methods play(), record(), and stream().

  • Lines 39–46: The Main class demonstrates the usage of the MediaPlayer class. It creates an instance of MediaPlayer and calls all three methods (play(), record(), stream()), each performing a distinct action.

Try this: Create a new interface called Downloadable with a method void download(String fileName).

Key takeaways

  1. A Java interface is a blueprint for defining common behavior across multiple classes, promoting abstraction and modularity.

  2. Interfaces support multiple inheritance, allowing a class to inherit behavior from multiple sources without the ambiguity found in multiple class inheritance.

  3. Use interfaces to design systems with loosely-coupled components, ensuring better scalability and maintainability.

  4. Avoid overloading interfaces with too many methods to keep the design clean and focused, aligning with the Single Responsibility Principle.

  5. When combining interfaces, ensure that each interface defines a distinct behavior to prevent confusion and tightly coupled implementations.

  6. Default methods introduced in Java 8 allow interfaces to evolve without breaking existing implementations, but they should be used judiciously to maintain simplicity.

  7. Avoid using interfaces for defining constants, as it leads to a poor design practice. Use dedicated classes or enums for this purpose.

Unlock your Java potential and take control of your coding journey! Start learning Java today to explore more than Java interfaces, build Java-based applications, and become a Java developer now!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


When should you use an interface in Java?

You should use an interface when:

  • You need to define a contract or standard behavior that multiple classes must implement.
  • You want to achieve abstraction without worrying about implementation details.
  • You require multiple inheritance since Java allows a class to implement multiple interfaces.
  • You are designing APIs or frameworks where implementation may vary across different classes.

What is the purpose of an interface?

The purpose of an interface is to:

  • Define a set of methods that implementing classes must provide.
  • Facilitate abstraction by separating the “what” (method declarations) from the “how” (method implementations).
  • Enable polymorphism, allowing you to use objects of different classes interchangeably through a common interface.
  • Encourage modular and maintainable code by standardizing behaviors across unrelated classes.

What are the benefits of interfaces in Java?

  • Multiple inheritance: A class can implement multiple interfaces, inheriting behaviors from different sources.
  • Abstraction: Interfaces define “what to do,” not “how to do it,” enabling clean separation of concerns.
  • Polymorphism: Interfaces allow you to use different implementations interchangeably.
  • Flexibility: Interfaces enable extending functionality without affecting existing implementations.
  • Reusability: Common behaviors defined in an interface can be reused across multiple classes.
  • Standardization: Interfaces enforce a consistent structure, particularly useful in large projects or APIs.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved