Java Interfaces

Java 149 views Dec 01, 2025 2 min read

In Java, an interface is a reference type that is similar to a class but can only contain abstract methods (methods without a body) and constants. Interfaces are used to achieve abstraction and support multiple inheritance in Java.


1. Key Features of Interfaces

  • Declared using the interface keyword.

  • Cannot have instance variables (only public static final constants).

  • All methods are implicitly public and abstract`.

  • Supports multiple inheritance, as a class can implement multiple interfaces.

  • Helps achieve loose coupling and polymorphism.


2. Syntax of an Interface

interface Vehicle { int MAX_SPEED = 120; // constant void start(); // abstract method void stop(); // abstract method }

3. Implementing an Interface

A class uses the implements keyword to implement an interface. The class must provide implementation for all abstract methods.

class Car implements Vehicle { public void start() { System.out.println("Car started"); } public void stop() { System.out.println("Car stopped"); } } public class Test { public static void main(String[] args) { Car myCar = new Car(); myCar.start(); myCar.stop(); } }

4. Multiple Interface Implementation

A class can implement more than one interface, providing a way to achieve multiple inheritance.

interface Engine { void run(); } interface Horn { void blow(); } class Bike implements Engine, Horn { public void run() { System.out.println("Bike engine running"); } public void blow() { System.out.println("Bike horn blows"); } }

5. Advantages of Interfaces

  • Abstraction: Provides a contract that classes must follow.

  • Multiple Inheritance: Overcomes Java’s limitation of single class inheritance.

  • Loose Coupling: Changes in implementation do not affect interface users.

  • Polymorphism: Objects can be treated by the interface type.


6. Key Points

  • Variables in an interface are public, static, and final by default.

  • Methods in an interface are abstract and public by default.

  • An interface cannot be instantiated directly.

  • Java 8 onwards, interfaces can also have default and static methods with implementation.


7. Conclusion

Interfaces in Java define a contract or blueprint for classes. They promote abstraction, modularity, and multiple inheritance, making programs more flexible, maintainable, and scalable. Mastery of interfaces is crucial for designing robust Java applications.

Some advanced sections are available for Registered Members
Share this Post
🚀 Want to Test Your Knowledge?

Take quizzes related to this topic and see where you stand!

Start Quiz Now
Back to Tutorials