- What is an Interface in Java?
- Key Points:
- Syntax of Interface
- Real-Life Analogy of Interface
- Example 1: Basic Interface and Implementation
- Output:
- Explanation:
- Interface: Animal
- Implementing Classes: Dog and Cat
- Main Method
- Example 2: Interface in Java – SmartHome Devices
- Explanation
- What is SmartDevice?
- What are SmartLight and SmartFan?
- Why use an interface here?
- Why Use Interfaces in Java?
- Multiple Inheritance Using Interface
- Output:
- Explanation:
- In this example:
- In the main() method:
- Default and Static Methods in Interface (Java 8+)
- 1. Default Methods in Interface
- Syntax
- Example: SmartAppliance
- Explanation:
- 2. Static Methods in Interface
- Syntax:
- Example: MathOperations
- Explanation:
- Private Methods in Interface (Java 9+)
- Output:
- Explanation:
- Interface: UnitConverter
- Why Use Static Methods in Interfaces?
- Main Class:
- Interface vs Abstract Class
- Interface as Polymorphic Type
- What is “Interface as Polymorphic Type”?
- Java Program – Using Interface as Polymorphic Type
- Explanation
- Benefits of Using Interface as Polymorphic Type
- Interface Inheritance (Interface extending another Interface)
- What is Interface Inheritance?
- Syntax of Interface Inheritance
- Real-World Analogy: “Smart Home Devices”
- Output:
- Explanation
- Practice Task
- Frequently Asked Questions (FAQs) about Java Interfaces
- 1️⃣ Can an interface have method implementations in Java?
- 2️⃣ Can a class implement multiple interfaces?
- 3️⃣ What happens if a class does not implement all methods of an interface?
- 4️⃣ Can interfaces extend other interfaces?
- 5️⃣ Can an interface have variables?
- 6️⃣ Why use interfaces when we have abstract classes?
- 7️⃣ Can an interface extend a class?
- 8️⃣ Can we create an object of an interface?
- 9️⃣ Can interface methods be private or protected?
- 🔟 Can a class implement the same interface more than once?
- Conclusion
In Java, interfaces are one of the most powerful features used to achieve abstraction and multiple inheritance. But what exactly is an interface? Why do we use it? And how is it different from abstract classes?
Let’s break everything down like you’re learning this in a tutorial, step by step with real examples, so that by the end of this guide, you’ll be confident with interfaces in Java.
What is an Interface in Java?
An interface in Java is a blueprint of a class. It is used to define a contract that classes must follow. The interface only contains method declarations (without a body) and constants. The actual implementation of the methods is done by the class that implements the interface.
Key Points:
- Interface is not a class, but a reference type in Java.
- Use the
interfacekeyword. - Interfaces cannot have constructors.
- It can only have abstract methods (until Java 7).
- From Java 8 onwards, it can have default and static methods with body.
- From Java 9, it can even have private methods.
- A class implements an interface using the
implementskeyword. - Java supports multiple interfaces (unlike classes).
Syntax of Interface
interface InterfaceName {
// abstract method
void method1();
// constant
int VALUE = 10;
// default method (Java 8+)
default void defaultMethod() {
System.out.println("Default Method");
}
// static method (Java 8+)
static void staticMethod() {
System.out.println("Static Method");
}
}
Real-Life Analogy of Interface
Think of an interface like a remote control. The remote only defines buttons (actions) — like volume up, volume down — but it doesn’t know how the TV will handle those actions. That’s up to the TV manufacturer (class implementing the interface).
Example 1: Basic Interface and Implementation
interface Animal {
void makeSound(); // abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof! Woof!");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow! Meow!");
}
}
public class Main {
public static void main(String[] args) {
Animal d = new Dog();
d.makeSound();
Animal c = new Cat();
c.makeSound();
}
}
Output:
Woof! Woof!
Meow! Meow!
Here, Dog and Cat both implement the Animal interface and provide their own version of makeSound().
Explanation:
Interface: Animal
- This interface defines a method:
void makeSound(); - It has no body, meaning it doesn’t say what sound to make.
- It acts like a blueprint that every animal class must follow.
Implementing Classes: Dog and Cat
- Both
DogandCatimplement theAnimalinterface. - Each class gives its own version of the
makeSound()method:- The Dog says:
"Woof! Woof!" - The Cat says:
"Meow! Meow!"
- The Dog says:
Main Method
Animal d = new Dog();
d.makeSound(); // Woof! Woof!
Animal c = new Cat();
c.makeSound(); // Meow! Meow!
- Even though the reference type is
Animal, the actual object is eitherDogorCat. - This is an example of runtime polymorphism.
- Java decides at runtime which version of
makeSound()to call — based on the actual object.
Example 2: Interface in Java – SmartHome Devices
Imagine you’re building a SmartHome system where different devices (like lights and fans) can be turned ON or OFF, but each device might behave differently. We’ll define an interface called SmartDevice that every smart appliance must implement.
// Interface
interface SmartDevice {
void turnOn();
void turnOff();
}
// Implementing class: Smart Light
class SmartLight implements SmartDevice {
public void turnOn() {
System.out.println("Smart Light is now ON.");
}
public void turnOff() {
System.out.println("Smart Light is now OFF.");
}
}
// Implementing class: Smart Fan
class SmartFan implements SmartDevice {
public void turnOn() {
System.out.println("Smart Fan is spinning.");
}
public void turnOff() {
System.out.println("Smart Fan is stopped.");
}
}
// Main class to test
public class SmartHome {
public static void main(String[] args) {
SmartDevice device1 = new SmartLight();
SmartDevice device2 = new SmartFan();
device1.turnOn(); // Smart Light is now ON.
device1.turnOff(); // Smart Light is now OFF.
device2.turnOn(); // Smart Fan is spinning.
device2.turnOff(); // Smart Fan is stopped.
}
}
Output
Smart Light is now ON.
Smart Light is now OFF.
Smart Fan is spinning.
Smart Fan is stopped.
Explanation
What is SmartDevice?
- It’s an interface — a common contract that says:
“Any device that is smart must be able to turn on and off.” - It declares two methods:
turnOn()andturnOff(), but doesn’t define how they work.
What are SmartLight and SmartFan?
- These are concrete classes that implement the
SmartDeviceinterface. - They provide their own version of what “turning on” and “turning off” means.
Why use an interface here?
- Imagine adding more smart devices in the future — like Smart TV, Smart AC, etc.
- As long as they implement
SmartDevice, the system knows how to interact with them — without changing existing code. - This follows the Open/Closed Principle (open for extension, closed for modification).
Why Use Interfaces in Java?
- To achieve 100% abstraction (until Java 7).
- To implement multiple inheritance (Java doesn’t allow multiple class inheritance).
- To define a standard structure or contract that different classes can follow.
- To support loose coupling and polymorphism.
Multiple Inheritance Using Interface
Java doesn’t allow a class to inherit from more than one class (to avoid the diamond problem), but it allows implementing multiple interfaces.
interface Engine {
void startEngine();
}
interface MusicSystem {
void playMusic();
}
// A class that implements multiple interfaces
class Car implements Engine, MusicSystem {
public void startEngine() {
System.out.println("Engine started with keyless push button.");
}
public void playMusic() {
System.out.println("Playing music: 'Drive Safe' playlist.");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.startEngine();
myCar.playMusic();
}
}
Output:
Engine started with keyless push button.
Playing music: 'Drive Safe' playlist.
Explanation:
In this example:
Engineand MusicSystem are two separate interfaces.- Both define abstract methods: startEngine() and playMusic().
- The class
Carimplements both interfaces, meaning it must define both methods.
In the main() method:
- We create an object of the
Carclass. - It starts the engine and plays music — combining behaviors from both interfaces.
Default and Static Methods in Interface (Java 8+)
With Java 8, interfaces became more powerful. Earlier, they could only declare abstract methods (no method body). But now, we can:
- Use default methods with a method body.
- Add static methods that can be called using the interface name.
Let’s explore both in detail with examples.
1. Default Methods in Interface
A default method in an interface allows you to provide a method body (implementation).
It was introduced to ensure backward compatibility when an interface is updated without breaking existing classes.
Syntax
interface InterfaceName {
default void methodName() {
// body
}
}
Example: SmartAppliance
interface SmartAppliance {
void turnOn();
default void showStatus() {
System.out.println("Status: All systems are working fine.");
}
}
class SmartFan implements SmartAppliance {
public void turnOn() {
System.out.println("Smart Fan is now ON.");
}
}
class SmartLight implements SmartAppliance {
public void turnOn() {
System.out.println("Smart Light is now ON.");
}
// Overriding default method
public void showStatus() {
System.out.println("Smart Light is dimmed to 50% brightness.");
}
}
public class Main {
public static void main(String[] args) {
SmartAppliance fan = new SmartFan();
fan.turnOn();
fan.showStatus();
SmartAppliance light = new SmartLight();
light.turnOn();
light.showStatus();
}
}
Output:
Smart Fan is now ON.
Status: All systems are working fine.
Smart Light is now ON.
Smart Light is dimmed to 50% brightness.
Explanation:
Interface:
SmartApplianceis an interface representing any smart device.- It has:
- An abstract method
turnOn(), which must be implemented by any class. - A default method
showStatus(), which provides a basic status message for smart appliances.
- An abstract method
Class: SmartFan
- Implements
SmartAppliance. - Provides its own version of
turnOn(). - Does not override
showStatus(), so it uses the default implementation from the interface.
Class: SmartLight
- Also implements
SmartAppliance. - Implements its own version of
turnOn(). - Overrides
showStatus()to give a more specific status (like brightness level).
Main Class:
- Creates objects of
SmartFanandSmartLight, but stores them in reference variables of theSmartAppliancetype (interface type). - Calls both
turnOn()andshowStatus()to demonstrate:- Default method usage (in
SmartFan). - Default method override (in
SmartLight).
- Default method usage (in
2. Static Methods in Interface
Java 8 allows static methods inside interfaces, which:
- Can be used for utility/helper methods.
- Are not inherited by implementing classes.
- Must be called using the interface name.
Syntax:
interface InterfaceName {
static void methodName() {
// body
}
}
Example: MathOperations
interface MathOperations {
static int square(int x) {
return x * x;
}
static int cube(int x) {
return x * x * x;
}
}
public class Main {
public static void main(String[] args) {
int num = 5;
System.out.println("Square of " + num + ": " + MathOperations.square(num));
System.out.println("Cube of " + num + ": " + MathOperations.cube(num));
}
}
Output:
Square of 5: 25
Cube of 5: 125
Explanation:
Interface: MathOperations
- Contains two static methods:
square(int x): returns the square of a number (x * x).cube(int x): returns the cube of a number (x * x * x).
- These methods are utility-like functions.
- Static methods in an interface belong to the interface itself and cannot be overridden.
Why Static in Interface?
- Introduced in Java 8.
- Allows defining helper or utility methods in interfaces.
- These methods are called using the interface name, not through objects.
Class: Main
- Declares an integer
num = 5. - Uses the interface name
MathOperationsto directly call:square(5)cube(5)
- Prints the results.
Private Methods in Interface (Java 9+)
Used to reduce code duplication inside default or static methods.
You’re building a utility for converting units like kilometers to miles and Celsius to Fahrenheit. Instead of creating a utility class, you use a Java interface with static methods.
interface UnitConverter {
static double kilometersToMiles(double km) {
return km * 0.621371;
}
static double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
static double gramsToOunces(double grams) {
return grams * 0.035274;
}
}
public class Main {
public static void main(String[] args) {
double distanceKm = 10;
double tempCelsius = 25;
double weightGrams = 500;
System.out.println(distanceKm + " km = " + UnitConverter.kilometersToMiles(distanceKm) + " miles");
System.out.println(tempCelsius + "°C = " + UnitConverter.celsiusToFahrenheit(tempCelsius) + "°F");
System.out.println(weightGrams + " grams = " + UnitConverter.gramsToOunces(weightGrams) + " ounces");
}
}
Output:
10.0 km = 6.21371 miles
25.0°C = 77.0°F
500.0 grams = 17.637 ounces
Explanation:
Interface: UnitConverter
- Contains 3 static methods:
kilometersToMiles(double km)celsiusToFahrenheit(double celsius)gramsToOunces(double grams)
- These are utility-like methods grouped logically for unit conversions.
- They are directly callable using the interface name.
Why Use Static Methods in Interfaces?
- Keeps your code organized and reusable.
- Makes sense when methods are independent of object state.
- Promotes clean separation of concerns.
Main Class:
- Demonstrates conversion of:
- Distance from kilometers to miles.
- Temperature from Celsius to Fahrenheit.
- Weight from grams to ounces.
- Uses static method calls like
UnitConverter.kilometersToMiles().
Interface vs Abstract Class
| Feature | Interface | Abstract Class |
|---|---|---|
| Inheritance | Implements | Extends |
| Methods | Only abstract (Java 7), default/static (Java 8+), private (Java 9+) | Can have both abstract and concrete methods |
| Constructor | ❌ No constructors | ✅ Can have constructors |
| Variables | Always public static final | Can be anything |
| Multiple Inheritance | ✅ Yes | ❌ No |
| Access Modifiers | Only public | Can have any |
Interface as Polymorphic Type
What is “Interface as Polymorphic Type”?
When a variable is declared using an interface type, and at runtime it refers to objects of classes implementing that interface, this is polymorphic behavior.
This is powerful because it lets us write flexible, reusable, and easily maintainable code.
You can use interface types to create polymorphic behavior.
Java Program – Using Interface as Polymorphic Type
interface Drawable {
void draw();
}
class Pencil implements Drawable {
public void draw() {
System.out.println("Drawing with Pencil 📝");
}
}
class Brush implements Drawable {
public void draw() {
System.out.println("Painting with Brush 🎨");
}
}
class Spray implements Drawable {
public void draw() {
System.out.println("Spraying with Airbrush 🌬️");
}
}
public class DrawingApp {
public static void main(String[] args) {
Drawable tool1 = new Pencil(); // Polymorphism in action
Drawable tool2 = new Brush();
Drawable tool3 = new Spray();
tool1.draw(); // Output: Drawing with Pencil
tool2.draw(); // Output: Painting with Brush
tool3.draw(); // Output: Spraying with Airbrush
}
}
Explanation
Drawableis an interface with one methoddraw().Pencil,Brush, andSprayare concrete classes that implementDrawable.- In the
main()method, the variable is of typeDrawablebut refers to different tool objects. - The
draw()method behaves differently based on the actual object type — this is polymorphism using an interface.
Benefits of Using Interface as Polymorphic Type
- Extensibility: Add new classes without changing existing code.
- Maintainability: Cleaner and more readable code.
- Flexibility: You can switch or extend behavior dynamically.
Interface Inheritance (Interface extending another Interface)
What is Interface Inheritance?
In Java, an interface can inherit from another interface using the extends keyword. This is called interface inheritance.
It allows you to build more modular, scalable, and organized code by breaking down responsibilities into layers.
Syntax of Interface Inheritance
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
Here, interface B inherits the method methodA() from interface A and also declares a new method methodB().
Any class that implements B must implement both methodA() and methodB().
Real-World Analogy: “Smart Home Devices”
Let’s imagine a Smart Home System.
SmartDevice: More advanced behavior (like internet control)
Device: Basic device behavior (like power on/off)
// Base interface
interface Device {
void turnOn();
void turnOff();
}
// Extended interface
interface SmartDevice extends Device {
void connectToWifi();
}
// Concrete class implementing SmartDevice
class SmartFan implements SmartDevice {
public void turnOn() {
System.out.println("SmartFan is ON 🔆");
}
public void turnOff() {
System.out.println("SmartFan is OFF 🌑");
}
public void connectToWifi() {
System.out.println("SmartFan connected to Wi-Fi 📶");
}
}
public class Main {
public static void main(String[] args) {
SmartDevice fan = new SmartFan();
fan.turnOn();
fan.connectToWifi();
fan.turnOff();
}
}
Output:
SmartFan is ON 🔆
SmartFan connected to Wi-Fi 📶
SmartFan is OFF 🌑
Explanation
Deviceis the base interface with basic operations.SmartDeviceextendsDeviceand adds smart features.SmartFanimplementsSmartDevice, so it must provide:- Basic features:
turnOn()andturnOff()(fromDevice) - Smart feature:
connectToWifi()(fromSmartDevice)
- Basic features:
This layered design mimics real-world upgrades — basic devices becoming smart!
Practice Task
Task: Create an interface Bank with a method getInterestRate() and implement it in SBI, HDFC, and ICICI classes. Each class should return a different interest rate.
Frequently Asked Questions (FAQs) about Java Interfaces
1️⃣ Can an interface have method implementations in Java?
Yes, starting from Java 8, interfaces can have:
- Default methods with implementation.
- Static methods with implementation.
However, they cannot have regular instance methods with a body unless they are declared as default or static.
2️⃣ Can a class implement multiple interfaces?
Yes! Unlike classes, Java supports multiple inheritance using interfaces.
A class can implement as many interfaces as it wants:
class MyClass implements InterfaceA, InterfaceB { ... }
3️⃣ What happens if a class does not implement all methods of an interface?
The class must be declared abstract.
Otherwise, the compiler will throw an error.
4️⃣ Can interfaces extend other interfaces?
Absolutely! Interfaces can extend one or more interfaces using the extends keyword:
interface B extends A, C { }
5️⃣ Can an interface have variables?
Yes, but all variables in an interface are:
publicstaticfinal
This means they’re constants and must be initialized at declaration.
6️⃣ Why use interfaces when we have abstract classes?
Use interfaces when:
- You need to achieve multiple inheritance.
- You only want to declare behavior (not share implementation).
- You need a contract-like structure across unrelated classes.
7️⃣ Can an interface extend a class?
❌ No.
An interface cannot extend a class, but it can extend another interface.
8️⃣ Can we create an object of an interface?
No.
Interfaces are abstract by nature. You cannot instantiate them directly.
You must use a class that implements the interface:
MyInterface obj = new MyClass(); // Valid
9️⃣ Can interface methods be private or protected?
Prior to Java 9: ❌ No
From Java 9 onward:
- Private methods are allowed inside interfaces (used as helper methods).
- Protected methods are still not allowed in interfaces.
🔟 Can a class implement the same interface more than once?
No, a class cannot implement the same interface multiple times. That would be redundant and the compiler will throw an error.
Conclusion
Java interfaces are fundamental for writing clean, flexible, and modular code. Whether you’re designing APIs, building plugins, or applying design patterns, interfaces will be your best friend. They allow multiple inheritance, enable abstraction, and promote code reusability.
Mastering interfaces gives you the power to design better systems and ace Java interviews too!