Introduction: Imagine a World Without Rules…
Think about a mobile phone. Every mobile can take photos, play music, make calls, and connect to the internet. Different brands like Samsung, Apple, and Xiaomi provide these features in their own unique ways.
But how do they all know what features they must provide?
The answer is a contract.
In Java, that contract is called an Interface.
An interface defines what a class must do, but it does not tell how it should do it.
What is an Interface in Java?
An Interface is a blueprint that contains method declarations that a class must implement.
It represents a promise or agreement between the interface and the class.
Interface says: "You must provide these functionalities."
Class says: "I will provide the implementation."
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
Real-World Example: The Remote Control
Imagine a TV Remote.
The remote has buttons like:
Power ON/OFF
Volume Control
Change Channel
The remote tells the TV what actions are available, but every TV company implements them differently.
Why Do We Need Interfaces?
- To Achieve Abstraction
Users know what an object can do, but they don't need to know how it does it.
Example:
You drive a car.
You know how to use the steering and brake.
You don't need to understand the engine mechanism.
- To Achieve Multiple Inheritance
A class can implement multiple interfaces.
Example:
A smartphone can be:
Camera
Music Player
Internet Device
- To Create Flexible Applications
One interface can have many implementations.
Characteristics of Interfaces
- Interface methods are public and abstract by default.
- Variables are public, static, and final by default.
- Interfaces cannot have constructors.
- Objects cannot be created directly from an interface.
- A class uses the implements keyword.
- One class can implement multiple interfaces.
- An interface can extend another interface.
- Since Java 8, interfaces can contain default and static methods.
Top comments (0)