Interface
Interface in Object-Oriented Programming
Learn what an interface is in Object-Oriented Programming, why interfaces are used, how they define contracts, how classes implement interfaces, and how interfaces support abstraction, polymorphism, flexibility, and clean software design.
Introduction
In Object-Oriented Programming, an interface is a very important concept used to define a common set of rules or behaviors that different classes must follow. An interface does not usually focus on how something is done. Instead, it focuses on what must be done.
In simple words, an interface acts like a contract. If a class agrees to follow an interface, then that class must provide implementation for the methods defined by the interface. This helps different classes follow the same structure while still allowing each class to write its own internal logic.
For example, suppose we are building a payment system. Different payment methods such as credit card, UPI, wallet, and net banking all perform payment, but each one works differently internally. We can create an interface named PaymentProcessor with a method called processPayment(). Each payment class can then implement this method in its own way.
Simple Definition of Interface
An interface is a structure in Object-Oriented Programming that defines a set of method signatures or required behaviors. A class that implements an interface must provide actual implementation for those methods.
In beginner-friendly words:
- An interface defines rules for classes.
- It tells what methods a class must have.
- It usually does not define the full internal logic.
- It supports abstraction by hiding implementation details.
- It supports polymorphism by allowing different classes to be used through the same interface.
- It makes software flexible, reusable, and easier to maintain.
Interface as a Contract
The best way to understand an interface is to think of it as a contract. A contract defines certain rules that must be followed. If a class signs that contract by implementing the interface, then the class must provide the required behavior.
For example, if an interface says that every payment class must have a method named processPayment(), then CreditCardPayment, UPIPayment, and WalletPayment must all provide that method.
Interface as a Contract
An interface is like a contract that says, "Any class that implements me must provide these methods." The class decides how those methods will work internally.
| Real-World Concept | Programming Concept | Explanation |
|---|---|---|
| Contract | Interface | Defines required rules or responsibilities. |
| Person signing contract | Class implementing interface | Agrees to follow the contract. |
| Contract conditions | Interface methods | Methods that must be implemented. |
| Actual work done | Method implementation | Logic written inside the implementing class. |
Why Do We Need Interfaces?
Interfaces are needed because in real-world software, many different classes may need to provide the same type of behavior, but each class may perform that behavior differently. An interface gives all those classes a common structure.
Without interfaces, code may become tightly connected to specific classes. This makes the application harder to change or extend. With interfaces, we can write code that depends on a common contract instead of depending on a specific class.
Without Interface
- Code may depend directly on specific classes.
- Adding new behavior may require changing existing code.
- Different classes may use inconsistent method names.
- Polymorphism becomes harder to apply.
- Large systems become less flexible.
- Testing and replacing components becomes difficult.
With Interface
- Classes follow a common contract.
- Code can work with different implementations.
- New classes can be added more easily.
- Polymorphism becomes easier to implement.
- System design becomes more flexible.
- Testing and replacing components becomes easier.
Main Idea Behind Interface
The main idea behind an interface is to separate the definition of behavior from the implementation of behavior. The interface defines what should exist. The implementing class defines how it should work.
For example, an interface can say that every notification class must have a method named send(). But EmailNotification sends email, SMSNotification sends SMS, and PushNotification sends push notification. The method name is common, but the internal implementation is different.
Basic Syntax Concept of Interface
The exact syntax of an interface depends on the programming language. However, the general concept is similar in many object-oriented languages.
// General conceptual syntax
Interface InterfaceName
{
methodName()
}
Class ClassName implements InterfaceName
{
methodName()
{
// actual implementation
}
}
In this conceptual example, the interface defines a method. The class that implements the interface provides the actual method body.
Interface Example: Payment System
Let us understand an interface using a payment system. In an e-commerce application, users can pay using different payment methods. All payment methods should support one common action: processPayment().
| Payment Class | Common Interface Method | Different Implementation |
|---|---|---|
| CreditCardPayment | processPayment() | Uses card number, CVV, bank approval. |
| UPIPayment | processPayment() | Uses UPI ID and bank confirmation. |
| WalletPayment | processPayment() | Uses wallet balance. |
| NetBankingPayment | processPayment() | Uses bank login and authentication. |
interface PaymentProcessor {
void processPayment(double amount);
}
class CreditCardPayment implements PaymentProcessor {
public void processPayment(double amount) {
System.out.println("Processing credit card payment of " + amount);
}
}
class UPIPayment implements PaymentProcessor {
public void processPayment(double amount) {
System.out.println("Processing UPI payment of " + amount);
}
}
class WalletPayment implements PaymentProcessor {
public void processPayment(double amount) {
System.out.println("Processing wallet payment of " + amount);
}
}
public class Main {
public static void main(String[] args) {
PaymentProcessor payment1 = new CreditCardPayment();
PaymentProcessor payment2 = new UPIPayment();
PaymentProcessor payment3 = new WalletPayment();
payment1.processPayment(1500);
payment2.processPayment(800);
payment3.processPayment(500);
}
}
In this example, PaymentProcessor is an interface. CreditCardPayment, UPIPayment, and WalletPayment all implement the interface and provide their own version of processPayment().
Java Example of Interface
In Java, an interface is declared using the interface keyword. A class implements an interface using the implements keyword. If a class implements an interface, it must provide implementation for the interface methods.
interface Printable {
void print();
}
class Invoice implements Printable {
public void print() {
System.out.println("Printing invoice");
}
}
class Report implements Printable {
public void print() {
System.out.println("Printing report");
}
}
class Certificate implements Printable {
public void print() {
System.out.println("Printing certificate");
}
}
public class Main {
public static void main(String[] args) {
Printable document1 = new Invoice();
Printable document2 = new Report();
Printable document3 = new Certificate();
document1.print();
document2.print();
document3.print();
}
}
In this example, Printable defines a common contract. Invoice, Report, and Certificate all implement Printable and provide their own print() method.
JavaScript Interface-Like Concept
JavaScript does not have traditional interfaces exactly like Java. However, interface-like behavior can be achieved by defining a base class or by following a common method structure across classes.
class NotificationSender {
send(message) {
throw new Error("send() method must be implemented");
}
}
class EmailNotification extends NotificationSender {
send(message) {
console.log("Sending email: " + message);
}
}
class SMSNotification extends NotificationSender {
send(message) {
console.log("Sending SMS: " + message);
}
}
class PushNotification extends NotificationSender {
send(message) {
console.log("Sending push notification: " + message);
}
}
const notifications = [
new EmailNotification(),
new SMSNotification(),
new PushNotification()
];
for (const notification of notifications) {
notification.send("Your order has been shipped.");
}
In this example, all notification classes follow the same expected method: send(). This creates interface-like behavior because each class provides its own implementation of the same action.
Interface and Abstraction
Interfaces are one of the most common ways to achieve abstraction in Object-Oriented Programming. An interface hides the implementation details and exposes only the required method names.
When code uses an interface, it does not need to know which specific class is performing the work. It only needs to know that the object follows the required contract.
For example, if a program uses PaymentProcessor, it does not need to know whether the payment is done through credit card, UPI, or wallet. It simply calls processPayment().
Interface and Polymorphism
Interfaces also support polymorphism. Multiple classes can implement the same interface, and objects of those classes can be treated as the interface type.
This means the same method call can work with different objects. Each object provides its own behavior.
interface Notification {
void send(String message);
}
class EmailNotification implements Notification {
public void send(String message) {
System.out.println("Email sent: " + message);
}
}
class SMSNotification implements Notification {
public void send(String message) {
System.out.println("SMS sent: " + message);
}
}
public class Main {
public static void main(String[] args) {
Notification notification1 = new EmailNotification();
Notification notification2 = new SMSNotification();
notification1.send("Welcome to the course");
notification2.send("Your OTP is 123456");
}
}
Here, notification1 and notification2 are both Notification interface references, but they point to different actual objects. The same send() method behaves differently.
Interface Members
Interfaces usually contain method declarations. Depending on the programming language, interfaces may also contain constants, default methods, static methods, or other members. However, beginner-level understanding should focus mainly on method contracts.
| Interface Member | Meaning | Beginner Example |
|---|---|---|
| Method Declaration | Defines method name and structure without full implementation. | void print(); |
| Constants | Fixed values that may be shared by implementing classes. | MAX_LIMIT |
| Default Method | A method with predefined implementation in some languages. | default displayInfo() |
| Static Method | A method that belongs to the interface itself in some languages. | InterfaceName.utilityMethod() |
Multiple Interfaces
Many programming languages allow a class to implement multiple interfaces. This is useful because one class may need to follow more than one contract.
For example, a SmartPrinter may be printable, scannable, and faxable. Instead of forcing all features into one large class hierarchy, we can define separate interfaces.
interface Printable {
void print();
}
interface Scannable {
void scan();
}
interface Faxable {
void fax();
}
class SmartPrinter implements Printable, Scannable, Faxable {
public void print() {
System.out.println("Printing document");
}
public void scan() {
System.out.println("Scanning document");
}
public void fax() {
System.out.println("Sending fax");
}
}
public class Main {
public static void main(String[] args) {
SmartPrinter printer = new SmartPrinter();
printer.print();
printer.scan();
printer.fax();
}
}
In this example, SmartPrinter implements three interfaces. This allows the class to provide multiple capabilities in a clean and organized way.
Interface and Multiple Inheritance Problem
Some object-oriented languages do not allow a class to inherit from multiple parent classes because it can create confusion. However, interfaces provide a cleaner way to achieve multiple behavior contracts.
A class may not be able to extend multiple classes in some languages, but it can often implement multiple interfaces. This helps avoid the complexity of multiple class inheritance while still allowing multiple capabilities.
Interface vs Abstract Class
Interfaces and abstract classes are both used for abstraction, but they are used in different situations. Beginners should understand when to use each one.
| Basis | Interface | Abstract Class |
|---|---|---|
| Main Purpose | Defines a contract or capability. | Defines a common base with partial implementation. |
| Focus | What a class must do. | What a related group of classes share. |
| Relationship | Represents can-do capability. | Represents is-a relationship. |
| Implementation | Usually implemented by classes. | Usually extended by child classes. |
| Multiple Usage | A class can often implement multiple interfaces. | A class often extends only one abstract class in many languages. |
| Example | Printable, Payable, Runnable | Animal, Vehicle, Shape |
Interface vs Class
A class and an interface are different. A class can contain data and implementation. An interface mainly defines rules or behavior that a class must implement.
| Basis | Class | Interface |
|---|---|---|
| Purpose | Creates objects and contains implementation. | Defines a contract for classes. |
| Object Creation | Objects can be created from normal classes. | Objects are usually not created directly from interfaces. |
| Methods | Can contain complete method implementation. | Usually declares required methods. |
| Properties | Can contain object properties. | Usually focuses on behavior contracts. |
| Example | Student, Car, Product | Printable, PaymentProcessor, NotificationSender |
Advantages of Interfaces
Interfaces provide several advantages in Object-Oriented Programming. They help design flexible systems where different classes can follow the same contract while having different implementations.
Benefits of Interfaces
- Abstraction: Interfaces hide implementation details and expose required behavior.
- Polymorphism: Different classes can be treated through the same interface type.
- Flexibility: New implementations can be added without changing existing code heavily.
- Loose Coupling: Code depends on contracts rather than specific classes.
- Better Testing: Interfaces make it easier to replace real implementations with test versions.
- Multiple Capabilities: A class can implement multiple interfaces in many languages.
- Clean Design: Interfaces separate what a system does from how it does it.
- Consistency: Different classes follow the same method structure.
- Scalability: New classes can be added more easily.
- Team Development: Teams can agree on interfaces before writing implementation.
Limitations of Interfaces
Interfaces are powerful, but they should be used properly. Overusing interfaces in simple programs can make the design unnecessarily complicated.
Interface Best Practices
Good interface design is very important. An interface should be focused, meaningful, and easy to implement. It should represent a clear capability or contract.
Best Practices for Interfaces
- Use interfaces when multiple classes share a common behavior.
- Keep interfaces small and focused.
- Use meaningful names such as Printable, Payable, Notifiable, or PaymentProcessor.
- Avoid putting unrelated methods in one interface.
- Use interfaces to reduce dependency on specific classes.
- Design interfaces around behavior, not data storage.
- Use interfaces for capabilities such as printable, sortable, readable, or payable.
- Do not create an interface unless it improves flexibility or clarity.
- Prefer clear method names that describe required behavior.
- Use interfaces to support polymorphism and clean architecture.
Common Mistakes Beginners Make
Beginners often confuse interfaces with classes or abstract classes. Understanding common mistakes helps build stronger object-oriented design skills.
Common Mistakes
- Thinking an interface is the same as a class.
- Trying to create objects directly from an interface.
- Creating interfaces without a clear purpose.
- Adding too many unrelated methods into one interface.
- Using interfaces when a simple class is enough.
- Forgetting to implement all required interface methods.
- Confusing interface implementation with class inheritance.
- Not understanding how interfaces support polymorphism.
Better Approach
- Remember that an interface defines a contract.
- Use interfaces for common behavior across different classes.
- Keep interfaces focused and meaningful.
- Implement all required methods properly.
- Use interface references for flexible code.
- Use abstract classes for shared base structure when needed.
- Use interfaces to represent capabilities.
- Practice with examples like Payment, Notification, and Printable.
How to Identify Interface Requirements
To identify whether an interface is needed, look for multiple classes that should provide the same action but may perform it differently.
Consider this requirement:
Here, all notification types have one common capability: send notification. So, we can create an interface:
interface NotificationSender {
void send(String message);
}
Then EmailNotification, SMSNotification, and PushNotification can implement this interface.
Example: Interface in Student Management System
In a student management system, different types of reports may need to be generated. For example, marks report, attendance report, and fee report all have a common action: generateReport(). But each report has different internal logic.
| Report Type | Common Interface Method | Specific Implementation |
|---|---|---|
| MarksReport | generateReport() | Calculates marks, grade, and result status. |
| AttendanceReport | generateReport() | Calculates attendance percentage and status. |
| FeeReport | generateReport() | Shows paid amount, due amount, and payment history. |
interface ReportGenerator {
void generateReport();
}
class MarksReport implements ReportGenerator {
public void generateReport() {
System.out.println("Generating marks report");
}
}
class AttendanceReport implements ReportGenerator {
public void generateReport() {
System.out.println("Generating attendance report");
}
}
class FeeReport implements ReportGenerator {
public void generateReport() {
System.out.println("Generating fee report");
}
}
public class Main {
public static void main(String[] args) {
ReportGenerator report1 = new MarksReport();
ReportGenerator report2 = new AttendanceReport();
ReportGenerator report3 = new FeeReport();
report1.generateReport();
report2.generateReport();
report3.generateReport();
}
}
This example shows how interfaces make it easy to use different report types through a common structure.
Real-World Software Examples of Interfaces
Interfaces are widely used in real-world software systems. They help create flexible designs where different components can be replaced or extended without changing the whole system.
| System | Possible Interface | Implementing Classes | Common Method |
|---|---|---|---|
| Payment System | PaymentProcessor | CreditCardPayment, UPIPayment, WalletPayment | processPayment() |
| Notification System | NotificationSender | EmailNotification, SMSNotification, PushNotification | send() |
| Report System | ReportGenerator | PDFReport, ExcelReport, HTMLReport | generateReport() |
| File Storage System | StorageService | LocalStorage, CloudStorage, DatabaseStorage | saveFile() |
| Authentication System | Authenticator | PasswordAuth, OTPAuth, BiometricAuth | authenticate() |
Mini Practice Activity
Try to identify suitable interfaces from the following scenarios. This exercise will help you understand how interfaces are used in real projects.
| Scenario | Possible Interface | Required Method | Possible Implementing Classes |
|---|---|---|---|
| Different payment methods | PaymentProcessor | processPayment() | CreditCardPayment, UPIPayment, WalletPayment |
| Different notification channels | NotificationSender | send() | EmailNotification, SMSNotification, PushNotification |
| Different report formats | ReportExporter | exportReport() | PDFExporter, ExcelExporter, CSVExporter |
| Different login methods | Authenticator | authenticate() | PasswordAuth, OTPAuth, BiometricAuth |
| Different printable documents | Printable | print() | Invoice, Certificate, Report |
| Different file storage systems | StorageService | saveFile() | LocalStorage, CloudStorage, DatabaseStorage |
Frequently Asked Questions
1. What is an interface in simple words?
An interface is a contract that defines what methods a class must provide. It tells what should be done, but the implementing class decides how it will be done.
2. Why do we use interfaces?
Interfaces are used to achieve abstraction, support polymorphism, reduce dependency on specific classes, and create flexible software designs.
3. Can we create an object of an interface?
In many object-oriented languages, we cannot directly create an object of an interface. However, we can use an interface reference to refer to an object of a class that implements the interface.
4. What does it mean to implement an interface?
Implementing an interface means a class agrees to provide actual code for all required methods defined by the interface.
5. What is the difference between an interface and a class?
A class can contain data and full implementation. An interface mainly defines a contract or required behavior that classes must implement.
6. What is the difference between an interface and an abstract class?
An interface usually defines a behavior contract, while an abstract class provides a common base structure that may include both abstract and implemented methods.
7. Can a class implement multiple interfaces?
In many languages, yes. A class can implement multiple interfaces, allowing it to support multiple capabilities.
8. How do interfaces support polymorphism?
Different classes can implement the same interface. Then objects of those classes can be treated as the interface type, and the same method call can behave differently.
9. When should I use an interface?
Use an interface when multiple classes should follow the same behavior contract but may implement that behavior differently.
10. Is an interface only used in Java?
No. Many programming languages support interfaces or interface-like concepts. The syntax may differ, but the design idea is widely used in software development.
Summary
An interface is an important Object-Oriented Programming concept used to define a contract for classes. It specifies what methods a class must implement, but it does not usually define how those methods should work internally.
Interfaces support abstraction by hiding implementation details and showing only required behavior. They also support polymorphism because multiple classes can implement the same interface and provide different behavior for the same method.
Interfaces are useful in real-world software systems such as payment systems, notification systems, report generation systems, authentication systems, and file storage systems. They help make code flexible, reusable, testable, and easier to maintain.
Key Takeaway
An interface is a contract that defines required behavior for classes. It focuses on what should be done, while implementing classes decide how it should be done. Interfaces support abstraction, polymorphism, loose coupling, and flexible software design.