4. Interfaces in Java
Defining contracts for classes, implementing multiple interfaces, and comparing Abstract Class vs Interface.
What is an Interface?
English Definition
An Interface is a blueprint of a class that defines a contract which implementing classes must follow.
Hinglish Explanation
Interface mein hum methods declare karte hain aur jo class use
implements karti hai, woh un methods ko define karti hai.
Real-Life Analogy: Remote Control
Think of a TV Remote Control as an interface—it defines the buttons (contract), while different TV brands implement what happens when you press them:
- Power ON
- Power OFF
- Volume Up
Main.java — Vehicle Interface (Car & Bike)
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting");
}
public void stop() {
System.out.println("Car is stopping");
}
}
class Bike implements Vehicle {
public void start() {
System.out.println("Bike is starting");
}
public void stop() {
System.out.println("Bike is stopping");
}
}
class Main {
public static void main(String args[]) {
Vehicle v1 = new Car();
v1.start();
v1.stop();
Vehicle v2 = new Bike();
v2.start();
v2.stop();
}
}
Console OutputCar is starting
Car is stopping
Bike is starting
Bike is stopping
Real-Life Multiple Interface Example: SmartPhone
A single class in Java can implement multiple interfaces separated by a comma.
«interface» Camera
«interface» MusicPlayer
⬇ implements ⬇
SmartPhone
Main.java — SmartPhone Implementing Camera & MusicPlayer
interface Camera {
void takePhoto();
void recordVideo();
}
interface MusicPlayer {
void playMusic();
void stopMusic();
}
class SmartPhone implements Camera, MusicPlayer {
public void takePhoto() {
System.out.println("Taking photo");
}
public void recordVideo() {
System.out.println("Recording Video");
}
public void playMusic() {
System.out.println("Music playing");
}
public void stopMusic() {
System.out.println("Music stopped");
}
}
class Main {
public static void main(String args[]) {
SmartPhone s = new SmartPhone();
s.takePhoto();
s.recordVideo();
s.playMusic();
s.stopMusic();
}
}
Console OutputTaking photo
Recording Video
Music playing
Music stopped
Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Declaration Keyword | abstract keyword |
interface keyword |
| Inheritance Keyword | extends keyword |
implements keyword |
| Constructor | Constructor ho sakta hai (Can have constructors) | Constructor nahi hota (Cannot have constructors) |
| Methods | abstract aur normal methods dono ho sakte hain |
abstract, default, aur static methods |
| Variables / Fields | Instance variables ho sakte hain | Fields automatically public static final hote hain |
| Multiple Inheritance | Ek class ek hi class extend kar sakti hai |
Ek class multiple interfaces implement kar sakti hai |