Interface in Java
An interface in Java is a blueprint or contract that defines a set of operations for implementing classes. A concrete implementing class must provide or inherit implementations of the interface's abstract methods.
An interface mainly defines what a class should do, while the implementing class defines how it should do it.
Interfaces are widely used in Java to achieve abstraction, loose coupling, flexibility, and multiple inheritance of type.
What is an Interface in Java?
An interface is declared using the interface keyword.
interface Payment {
void pay();
}Here, Payment is an interface and pay() is a method declared in the interface.
A class can implement an interface using the implements keyword.
class UPI implements Payment {
@Override
public void pay() {
System.out.println("Payment made using UPI");
}
}The Payment interface defines the rule:
Every Payment must provide a pay() method.The UPI class decides how the pay() method should work.
Why Do We Need Interfaces?
Interfaces are useful when we want to define a common contract for different classes.
Consider different payment methods:
Payment
|
-----------------------
| | |
UPI CreditCard DebitCardAll payment methods need to perform a payment, but the implementation can be different.
We can define the common behavior in an interface:
interface Payment {
void pay();
}Then each class can provide its own implementation:
class UPI implements Payment {
@Override
public void pay() {
System.out.println("Payment made using UPI");
}
}
class CreditCard implements Payment {
@Override
public void pay() {
System.out.println("Payment made using Credit Card");
}
}The interface ensures that every payment method provides a pay() method.
Interface as a Contract
An interface can be thought of as a contract.
For example:
interface Vehicle {
void start();
}This means:
A concrete class implementing Vehicle must provide or inherit an implementation of start().For example:
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car starts with a key");
}
}Another class can implement the same interface differently:
class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike starts with a button");
}
}The interface defines the requirement, while the classes provide the implementation.
Basic Syntax
The basic syntax of an interface is:
interface InterfaceName {
// method declarations
}A class implements the interface using:
class ClassName implements InterfaceName {
// method implementations
}Example
interface Animal {
void makeSound();
}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}How Does an Interface Work?
Let's understand the process step by step.
Step 1: Define the interface
interface Payment {
void pay();
}The interface defines what functionality is required.
Step 2: Implement the interface
class UPI implements Payment {
@Override
public void pay() {
System.out.println("Payment using UPI");
}
}The class provides the implementation.
Step 3: Create the object
Payment payment = new UPI();Here, Payment is the interface reference and UPI is the actual object.
Step 4: Call the method
payment.pay();Java executes the implementation provided by UPI.
Output
Payment using UPIComplete Example
interface Payment {
void pay();
}
class UPI implements Payment {
@Override
public void pay() {
System.out.println("Payment made using UPI");
}
}
class CreditCard implements Payment {
@Override
public void pay() {
System.out.println("Payment made using Credit Card");
}
}
public class HelloWorld {
public static void main(String[] args) {
Payment payment = new UPI();
payment.pay();
payment = new CreditCard();
payment.pay();
}
}Output
Payment made using UPI
Payment made using Credit CardNotice that the same reference:
Payment payment;can refer to different implementations.
This provides flexibility and is an example of polymorphism.
Interface and Abstraction
Interfaces are commonly used to achieve abstraction.
For example:
interface Payment {
void pay();
}The interface tells us:
What → pay()But it does not need to expose the internal details of how the payment is processed.
The implementation is provided by the class:
class UPI implements Payment {
@Override
public void pay() {
// Internal payment processing
System.out.println("Payment made using UPI");
}
}Therefore, an interface provides abstraction by defining what a class should do while allowing the class to define how it should do it.
Interface Provides Loose Coupling
One of the important uses of interfaces is loose coupling.
Consider this code:
class OrderService {
private UPI payment = new UPI();
void placeOrder() {
payment.pay();
}
}OrderService is directly dependent on UPI.
If we want to change the payment method, we need to modify OrderService.
Instead, we can depend on the interface:
class OrderService {
private Payment payment;
OrderService(Payment payment) {
this.payment = payment;
}
void placeOrder() {
payment.pay();
}
}Now we can provide different implementations:
Payment payment = new UPI();
OrderService service = new OrderService(payment);
service.placeOrder();Or:
Payment payment = new CreditCard();
OrderService service = new OrderService(payment);
service.placeOrder();OrderService does not need to know which payment implementation is being used.
This is called loose coupling.
Multiple Interfaces
A Java class can implement multiple interfaces.
This is one of the important advantages of interfaces.
interface Printable {
void print();
}
interface Scannable {
void scan();
}
class Printer implements Printable, Scannable {
@Override
public void print() {
System.out.println("Printing document");
}
@Override
public void scan() {
System.out.println("Scanning document");
}
}Here:
class Printer implements Printable, Scannablemeans that Printer implements both interfaces.
Therefore, a Java class can implement multiple interfaces.
Interface Can Extend Another Interface
An interface can extend another interface using the extends keyword.
interface Vehicle {
void start();
}
interface ElectricVehicle extends Vehicle {
void charge();
}Now a concrete class implementing ElectricVehicle must provide or inherit implementations for both methods:
class ElectricCar implements ElectricVehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void charge() {
System.out.println("Car is charging");
}
}An interface can also extend multiple interfaces:
interface A {
void methodA();
}
interface B {
void methodB();
}
interface C extends A, B {
void methodC();
}Methods in an Interface
Modern Java interfaces can contain different types of methods.
1. Abstract Methods
An interface method declared without a body, and without private, default, or static, is implicitly public and abstract.
interface Vehicle {
void start();
}A concrete implementing class must provide or inherit a public implementation:
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
}2. Default Methods
Since Java 8, an interface can have a method with an implementation using the default keyword.
interface Vehicle {
void start();
default void stop() {
System.out.println("Vehicle stopped");
}
}The implementing class does not have to override stop().
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
}Usage:
Car car = new Car();
car.start();
car.stop();Output
Car started
Vehicle stoppedA class can also override the default method:
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}Static Methods in an Interface
Since Java 8, an interface can also contain static methods.
interface Calculator {
static int add(int a, int b) {
return a + b;
}
}A static interface method is called using the interface name:
int result = Calculator.add(10, 20);
System.out.println(result);Output
30It is not called through an implementing class object.
Private Methods in an Interface
Since Java 9, interfaces can also contain private methods.
They are useful for sharing implementation logic between methods inside the interface.
interface Payment {
default void pay() {
validate();
System.out.println("Payment processed");
}
private void validate() {
System.out.println("Validating payment");
}
}The private method can only be accessed from within the interface.
Variables in an Interface
Variables declared in an interface are implicitly:
public static finalFor example:
interface Configuration {
int MAX_USERS = 100;
}This is equivalent to:
interface Configuration {
public static final int MAX_USERS = 100;
}Therefore, the value cannot be changed:
Configuration.MAX_USERS = 200; // ErrorInterface fields are public, static, and final, so they cannot be reassigned. A final field that refers to an object does not make that object immutable. Only final primitive or String variables initialized with constant expressions are compile-time constants.
Can We Create an Object of an Interface?
No, we cannot directly create an object of an interface.
Payment payment = new Payment(); // ❌ ErrorBut we can create an object of a class that implements the interface:
Payment payment = new UPI(); // ✅The object is created from an implementing class, not directly from the interface. The class can provide method implementations or inherit them, including applicable default methods.
Interface Reference and Object
Consider:
Payment payment = new UPI();There are two different parts here:
Payment payment = new UPI();
↑ ↑
Reference ObjectPayment is the interface type.
UPI is the actual object type.
When we call:
payment.pay();Java executes the pay() implementation provided by UPI.
This is an example of runtime polymorphism.
Interface vs Abstract Class
Both interfaces and abstract classes can be used for abstraction, but they serve different purposes.
| Feature | Interface | Abstract Class |
|---|---|---|
| Keyword | interface | abstract class |
| Implementation | Can have abstract, default, static and private methods | Can have abstract and concrete methods |
| Instance variables | No instance variables; fields are public static final | Can have instance variables |
| Constructor | No constructor | Can have constructor |
| Multiple inheritance | A class can implement multiple interfaces | A class can extend only one class |
| HelloWorld purpose | Define a contract/capability | Provide a common base with shared behavior |
When Should You Use an Interface?
Use an interface when:
1. You want to define a contract
interface Payment {
void pay();
}Every payment implementation must follow this contract.
2. Different, potentially unrelated classes need the same capability
interface Printable {
void print();
}Different classes can implement Printable.
3. You want loose coupling
Instead of depending directly on a concrete class:
UPI payment;depend on the abstraction:
Payment payment;4. You need multiple types or capabilities
A class can implement multiple interfaces:
class SmartPhone implements Camera, GPS, MusicPlayer {
// ...
}Real-World Example
Consider a notification system.
We may have:
Notification
|
-------------------------
| | |
Email SMS PushDefine the interface:
interface Notification {
void send(String message);
}Email implementation:
class EmailNotification implements Notification {
@Override
public void send(String message) {
System.out.println("Sending email: " + message);
}
}SMS implementation:
class SMSNotification implements Notification {
@Override
public void send(String message) {
System.out.println("Sending SMS: " + message);
}
}Push notification implementation:
class PushNotification implements Notification {
@Override
public void send(String message) {
System.out.println("Sending push notification: " + message);
}
}Now the application can work with the interface:
Notification notification;
notification = new EmailNotification();
notification.send("Welcome!");
notification = new SMSNotification();
notification.send("Your OTP is ready.");
notification = new PushNotification();
notification.send("You have a new notification.");The application does not need to depend on the internal details of each notification system.
Advantages of Interfaces
1. Provides Abstraction
Interfaces expose the required functionality while hiding implementation details.
2. Supports Loose Coupling
Code can depend on an interface instead of a specific implementation.
3. Supports Multiple Implementations
Different classes can implement the same interface in different ways.
4. Supports Multiple Inheritance of Type
A class can implement multiple interfaces.
class SmartPhone implements Camera, GPS {
}5. Improves Flexibility
We can replace one implementation with another without changing code that depends only on the interface.
For example:
Payment payment = new UPI();can be changed to:
Payment payment = new CreditCard();The code using Payment can remain the same.
6. Useful for Large Applications
Interfaces help separate what a component does from how it does it, making large applications easier to design and modify.
Important Rules of Interfaces
Remember these important points:
- An interface is declared using the interface keyword.
- A class implements an interface using implements.
- A class can implement multiple interfaces.
- An interface cannot be directly instantiated.
- Interface fields are implicitly public, static, and final.
- Abstract interface methods are implicitly public and abstract.
- Interfaces can contain default methods with implementations.
- Interfaces can contain static methods.
- Interfaces can contain private methods for internal helper logic.
- An interface can extend one or more interfaces.
Interface in Simple Words
Think of an interface as a contract.
For example:
interface Payment {
void pay();
}The contract says:
"Any class that wants to be a Payment must provide a pay() operation."Different classes can fulfill that contract differently:
UPI → pay using UPI
CreditCard → pay using Credit Card
DebitCard → pay using Debit CardThe interface defines what is required, while the implementing class defines how it is performed.
Key Takeaway
An interface in Java is a contract that defines a set of operations that implementing classes must provide. It is mainly used for abstraction, loose coupling, flexibility, and allowing different classes to provide different implementations of the same functionality.
Remember
Interface ↓ Defines WHAT should be done ↓ Implementing class ↓ Defines HOW it should be done
See you in next page....🙂