Java Interfaces

What is an Interface?

An interface is a blueprint that defines what methods a class must have.

Interfaces are used for abstraction. This means they describe what a class should do without fully explaining how it should do it.

Loading...
Output:

Implementing an Interface

A class uses the implements keyword to follow an interface.

When a class implements an interface, it must provide code for the interface methods.

Loading...
Output:

Using Interface References

You can use an interface type as a reference variable. This allows your code to work with many different classes that implement the same interface.

In this example, Animal is the reference type, but the actual object is a Dog.

Loading...
Output:

Multiple Interfaces

Java does not allow a class to extend multiple classes, but one class can implement multiple interfaces.

This is useful when a class needs to support multiple behaviors, such as flying and swimming.

Loading...
Output:

Default Methods

Interfaces can include default methods. A default method has a body and can be used directly by classes that implement the interface.

A class can also override the default method if it needs custom behavior.

Loading...
Output:

Static Methods in Interfaces

Interfaces can also have static methods. These methods belong to the interface itself, not to an object.

To call a static interface method, use the interface name followed by the method name.

Loading...
Output:

Interfaces vs Classes

Classes and interfaces are both used to organize code, but they have different purposes.

A class usually stores data and behavior. An interface focuses on defining behavior that other classes must follow.

  • Class: used to create objects
  • Interface: used to define required behavior
  • extends: used for class inheritance
  • implements: used for interfaces

Why Use Interfaces?

Interfaces make your code more flexible because different classes can follow the same structure while having different implementations.

For example, an Employee and a Freelancer can both be Payable, even if their pay is calculated differently.

  • They support abstraction
  • They make code easier to extend
  • They allow different classes to share common behavior
  • They help reduce tight coupling between classes

Practice

Create an interface called Payable with a method calculatePay(). Then create Employee and Freelancer classes that implement it.

Loading...
Output:

Need Help?