DEV Community

Murali Rajendran
Murali Rajendran

Posted on

Interface in Java

🧠 What is an Interface?

1.An interface in Java is a blueprint of a class that defines a set of abstract methods (no body) which must be implemented by any class that uses (implements) the interface.
2.It is used to achieve abstraction and multiple inheritance.
3.Bydefault all methods are abstract method.
4.Its a set of rules and interface is a Keyword
5.Implementation: To implement an interface, we use the keyword implements

interface Animal {
void eat(); // abstract method
void sleep(); // abstract method
}

class Dog implements Animal {
public void eat() { System.out.println("Dog is eating..."); }
public void sleep() { System.out.println("Dog is sleeping..."); }
}

✅ What You Can Do with Interfaces

✔️ Define abstract methods (implicitly public and abstract).

✔️ Define public static final constants (variables).

✔️ Provide default methods (with body) using default keyword.

✔️ Provide static methods (with body).

✔️ Achieve multiple inheritance (a class can implement multiple interfaces).

✔️ Achieve 100% abstraction (if only abstract methods are used).

interface Vehicle {
void start();
default void stop() { System.out.println("Vehicle stopped"); }
static void info() { System.out.println("Vehicle interface"); }
}

❌ What You Cannot Do with Interfaces

❌ Cannot have instance variables (only public static final).

❌ Cannot have constructors (cannot create object directly).

❌ Cannot contain method implementations (except default and static).

❌ Cannot extend classes (but can extend other interfaces).

❌ Cannot maintain state — only define behavior.

interface A { void show(); }
interface B { void display(); }

class C implements A, B {
public void show() { System.out.println("Show from A"); }
public void display() { System.out.println("Display from B"); }
}

Example

Let’s consider the example of Vehicles like bicycles, cars and bikes share common functionalities, which can be defined in an interface, allowing each class (e.g., Bicycle, Car, Bike) to implement them in its own way. This approach ensures code reusability, scalability and consistency across different vehicle types.

Top comments (0)