Skip Top Navigation Bar

Implementing Interfaces

An interface defines a set of methods that a class agrees to implement. It describes what an object can do without specifying how it does it. Interfaces help you write flexible, reusable code because different classes can provide their own implementations of the same interface.

An interface contains method declarations, and any class that implements the interface must provide an implementation for each method.

Interfaces allow multiple classes to share a common set of behaviors without requiring them to inherit from the same superclass.

Code that works with objects of this interface does not need to change if another class is added that implements the interface. It can use any class that implements the interface.

Difference between Superclass and Interface

Both interfaces and superclasses let multiple classes share a common type, but they serve different purposes.

A superclass represents what objects are and can provide shared state and behavior. An interface represents what objects can do by defining a common capability.

Declaring an Interface

We use the keyword interface to declare an interface.

Let's consider a Shape interface. Each shape type has an area, so the Shape interface contains a method declaration for calculating the area. Each class that implements the Shape interface, would need to implement the method to calculate the area.

Basic Format:

Shape Example

Implementing an Interface

Use the implements keyword to indicate that a class implements an interface.

Basic Format:

Circle Example

Put it All Together

Let's try this in the Java Playground!