Interfaces in Java

Learn what an interface is and how it works in Java.

Introduction

As previously discussed, Java does not allow multiple inheritance. Only single and multi-level inheritance is allowed. What if a class needs to inherit properties from two classes that aren’t related to each other?

Consider a fundamental real-life example. A baby inherits characteristics from both the father and mother, but the father and mother don’t hold a parent-child relationship. Many computing applications include the idea of multiple inheritance. For this, Java provides another building block: an interface.

What is an interface?

An interface is a completely abstract class that is used to group related methods with empty bodies. Unlike an abstract class, an interface only has abstract methods.

Explanation

Look at the snippet below.

public interface Interface1
{
    int i = 0;
  
    void print();
}

The interface keyword is reserved to make interfaces in Java. Here, Interface1 is an interface with a variable and an abstract method. Remember: all variables in an interface are public, static, and final by default.

⚙️ Note: The final keyword with a variable means that its value can’t be modified in the future. Click here for more details.

Look at another interface below.

public interface Interface2
{
    String str = "Hello!";
  
    void printGreeting();
}

Here, Interface2 is an interface with a variable and an abstract method.

⚙️ Note: For your information, an abstract class can implement an interface.

Now let’s write a class that implements the two interfaces above:

Get hands-on with 1400+ tech skills courses.