Interface in Java with Example

An interface in Java is a reference type syntactically similar to a class but declared with the interface keyword. Before Java 8, an interface can have only abstract methods declaration and constants as members. By default, all variables in an interface are public static final, and all methods are public abstract.

Earlier to Java 8, an interface could not define any implementation whatsoever. An interface can only contain abstract methods. Java 8 changed this rule. To support lambda functions and functional programming,, Java 8 has added a new feature to interface.

You can also declare default methods and static methods inside interfaces. From Java 9 onwards, an interface can also contain private methods to share code between default methods.

Every interface in Java is abstract by default. So, it is not compulsory to write abstract keyword with an interface. Once an interface is defined, we can create any number of separate classes and can provide their own implementation for all the abstract methods defined by an interface.

A class that implements an interface is called implementation class. A class can implement any number of interfaces in Java. Every implementation class can have its own implementation for abstract methods specified in the interface as shown in the below figure.

Java Interface and its implementation classes

Since the implementation classes will have all the methods with a body, it is possible to create an instance of implementation classes.

Why do We Use Interfaces in Java?


There are several important reasons or purposes of using an interface in Java:

1. Designing Contracts (Separation of Design and Implementation)

  • In software development, architects or senior developers often create interfaces that define the required methods.
  • These interfaces are then given to developers for writing classes by implementing interfaces provided.
  • This ensures a clear separation between interface (what needs to be done) and implementation class (how it will be done).

2. Exposing APIs to Other Projects

  • Interfaces are the best way to expose project APIs to some other projects. In other words, we can provide interface methods to the third-party vendors for their implementation.
  • For example, a bank like HDFC may expose an interface to shopping carts or third-party applications to allow integration without exposing internal implementation details.

3. Customizing Behavior for Different Objects

  • Interfaces allow you to customize features of software differently for different objects.
  • For example, multiple classes can implement the same interface differently, enabling flexible and customized behavior.

4. Achieving Abstraction

  • Interfaces are used to achieve abstraction in Java.
  • Before Java 8, interfaces provided 100% abstraction (only method declarations).
  • After Java 8, they can also contain method implementations (via default and static methods).

5. Supporting Multiple Inheritance

  • Java does not allow multiple inheritance with classes to avoid the diamond problem.
  • By using interfaces, we can achieve the functionality of multiple inheritance safely.

How to Declare Interface in Java?


In Java, an interface is declared syntactically much like a class. It is declared by using the keyword interface followed by interface keyword. It has the following general form:

accessModifier interface interfaceName 
{
   // Declare constant fields.
   // Declare methods that abstract by default.
}

Before interface keyword, we can specify access modifiers such as public, or default with abstract keyword. Let’s understand the declaration of an interface with the help of an example.

public abstract interface MyInterfac
{
  int x = 10; // public static final keyword invisibly present.
  void m1(); // public and abstract keywords invisibly present.
  void m2();
}

As you can see in the above example, both methods m1() and m2() defined in interface are declared with no body and do not have public or abstract modifiers present. The variable x declared in MyInterface is like a simple variable.


Java compiler automatically adds public and abstract keywords before to all interface methods. Moreover, it also adds public, static, and final keywords before interface variables. Look at the below figure to understand better.
Internal addition of public, static, and final before variables by Java compiler.Therefore, all the variables declared in an interface are considered as public, static, and final by default and acts like constant. We cannot change their value once they initialized.

Features of Interface in Java


There are the following features of an interface in Java:

  • Interface provides pure abstraction in Java. It also represents the Is-A relationship between classes and interfaces.
  • An interface can contain four types of methods: abstract, default, static methods, and private methods.
  • All the (non-default, non-static) methods declared in Java interface are by default abstract and public. So, there is no need to write abstract or public modifiers before them.
  •  The fields (data members) declared in an interface are by default public, static, and final. Therefore, they are just public constants. So, we cannot change their value by implementing class once they are initialized.
  • An interface cannot have constructors because it cannot be instantiated directly.
  • Interfaces are the only mechanism in Java that allows achieving multiple inheritance of type.
  • A Java class can implement any number of interfaces by using keyword implements.
  • Interface can extend an interface and can also extend multiple interfaces.

Rules of Interface in Java


Here are some key points for defining an interface in Java that must be kept in mind. The rules are as follows:

  1. An interface cannot be instantiated directly. However, you can create a reference to an interface type that points to an object of a class implementing it.
  2. An interface may not be declared with final keyword because it is meant to be implemented by other classes.
  3. It cannot have instance variables. If you declare a variable in an interface, it must be initialized at the time of declaration.
  4. A class that implements an interface must provide its own implementations of all the methods defined in the interface.
  5. You cannot reduce the visibility of an interface method while overriding. That is, when you implement an interface method, it must be declared as public.
  6. An interface can also be declared with an empty body (i.e. without any members). For example, java.util package defines EventListener interface without a body.
  7. An interface can be declared within another interface or class. Such interfaces are called nested interfaces in Java.
  8. A top-level interface can be public or default with the abstract modifier in its definition. Therefore, an interface declared with private, protected, or final will generate a compile-time error.
  9. All non-default methods defined in an interface are abstract and public by default. Therefore, a method defined with private, protected, or final in an interface will generate compile-time error.
  10. If you add any new method in interface, all concrete classes which implement that interface must provide implementations for newly added method because all methods in interface are by default abstract.

Extending Interface in Java with Example


Like classes, an interface can also extend another interface in Java. This means that an interface can be sub interfaces from other interfaces.


The new sub-interface will inherit all members of the super interface similar to subclasses. It can be done by using the keyword “extends”. It has the following general form:

interface interfaceName2 extends interfaceName1
{
    // body of interfaceName2.
}

Look at the below figure a, b, c, and d to understand better.

Various forms of extending interface in Java

Example of Extending Interface

1. We can define all the constants in one interface and methods in another interface. We can use constants in classes where methods are not required. Look at the example below.

interface A 
{ 
  int x = 10; 
  int y = 20; 
 } 
interface B extends A 
{ 
  void show(); 
}

The interface B would inherit both constants x and y into it.

2. We can also extend various interfaces together by a single interface. The general declaration is given below:

interface A 
{ 
  int x = 20; 
  int y = 30; 
 } 
interface B extends A 
{ 
  void show(); 
 } 
interface C extends A, B 
{ 
  . . . . . . . . 
}

Key Points:

  1. An interface cannot extend classes because it would violate rules that an interface can have only abstract methods and constants.
  2. An interface can extend Interface1, Interface2.

Implementing Interface in Java with Example


An interface is used as “superclass” whose properties are inherited by a class. A class can implement one or more than one interface by using a keyword implements followed by a list of interfaces separated by commas.

When a class implements an interface, it must provide an implementation of all methods declared in the interface and all its super interfaces. Otherwise, the class must be declared abstract. The general syntax of a class that implements an interface is as follows:

accessModifier class className implements interfaceName 
{
  // Method implementations;
  // Member declaration of class;
}

A more general form of interface implementation is given below:

accessModifier class className extends superClass implements interface1, interface2,.. .
{
  // body of className.
}

This general form shows that a class can extend another class while implementing interfaces.

Key Points about Implementing Interface:

  • All methods of interfaces when implementing in a class must be declared as public otherwise, you will get a compile-time error if any other modifier is specified.
  • Class extends class implements interface.
  • Class extends class implements Interface1, Interface2 . . .

The implementation of interfaces can have the following general forms as shown in the below figure.
Various forms of interface implementation

Accessing Interface Variable in Java


The interface is also used to declare a set of constants that can be used in multiple classes. The constant values will be available to any classes that implement interface because it is by default public, static, and final.

We can use values in any method as part of the variable declaration or anywhere in the class. Let’s understand all important concepts of an interface with the help of various example programs.

Java Interface Example Programs


Example 1: Using Interface Constants in Multiple Classes

Let’s take an example program where multiple classes implement the same interface to use constant values declared in that interface.

package interfacePrograms; 
public interface ConstantValues 
{ 
// Declaration of interface variables. 
   int x = 20; 
   int y = 30; 
 } 
public class Add implements ConstantValues 
{ 
  int a = x; 
  int b = y; 
  void m1()
  { 
     System.out.println("Value of a: " +a); 
     System.out.println("Value of b: " +b); 
  } 
  void sum()
  { 
    int s = x + y; 
    System.out.println("Sum: " +s); 
  } 
} 
public class Sub implements ConstantValues 
{ 
  void sub()
  { 
    int p = y - x; 
    System.out.println("Sub: " +p); 
  } 
} 
public class Test 
{ 
  public static void main(String[] args) 
  { 
    Add a = new Add(); 
     a.m1(); 
     a.sum(); 
    Sub s = new Sub(); 
     s.sub(); 
   } 
}
Output: 
       Value of a: 20 
       Value of b: 30 
       Sum: 50 
       Sub: 10

Example 2: Interface Reference Pointing to Implementing Class Object

package interfacePrograms; 
public interface A 
{ 
   void msg(); // No body. 
} 
public class B implements A 
{ 
 // Override method declared in interface. 
    public void msg()
    { 
       System.out.println("Hello Java"); 
    } 
    void show()
    { 
       System.out.println("Welcome you"); 
    } 
   public static void main(String[] args) 
   { 
     B b = new B(); 
     b.msg(); 
     b.show(); // A reference of interface is pointing to objects of class B. 
    
     A a = new B(); 
     a.msg();

  // This statement will generate a compile-time error because 
  // a reference of interface can only call methods declared in it and implemented by implementing class.  
  // a.show(); 
 
  // show() method is not part of interface. It is part of class B. 
  // When you will call this method, the compiler will give a compile-time error. 
  // It can only be called when you create an object reference of class B. 
   }
}
Output: 
       Hello Java 
       Welcome you 
       Hello Java

Polymorphism in Java Interface


When two or more classes implement the same interface with different implementations, then through the object of each class, we can achieve polymorphic behavior for a given interface. By creating objects of each implementing class and calling the methods defined in the interface, the same method behaves different depending on the class. This concept is called polymorphism in interface.

In the above figure, (d) shows polymorphism in interfaces where class B and class C implement the same interface A.

Example: Polymorphism in Java using Interface and Multiple Implementations

package interfacePrograms;
public interface Rectangle 
{
   void calc(int l, int b); // no body.
}
public class RecArea implements Rectangle 
{
  public void calc(int l, int b) 
  {
     int area = l * b; // Implementation.
     System.out.println("Area of rectangle = "+area);
  }
}
public class RecPer implements Rectangle 
{
   public void calc(int l, int b) 
   {
     int perimeter = 2 * (l + b); // Implementation.
     System.out.println("Perimeter of rectangle = "+perimeter);
   }
}
public class Execution {
public static void main(String[] args) 
{
     Rectangle rc; // Creating an interface reference.
     rc = new RecArea(); // Creating object of RecArea.
     rc.calc(20, 30); // calling method.
  
     rc = new RecPer(); // Creating an object of RecPer.
     rc.calc(20, 30);
 }
}
Output: 
       Area of rectangle = 600
       Perimeter of rectangle = 100

As you can see in this program, multiple classes, such as RecArea and RecPer implement the same interface Rectangle with different implementations. This shows polymorphism in interface.

Multilevel Inheritance by Interface


Let’s take an example program in which we will create a multilevel inheritance by interface. If one interface extends an interface, that interface extends another interface, and a class implements methods of all interfaces, we can achieve multilevel inheritance by interfaces.

Example: Multilevel Inheritance in Java Interfaces

package interfacePrograms; 
public interface Continent 
{ 
  void showContinent(); 
} 
public interface Country extends Continent
{ 
  void showCountry(); 
} 
public interface State extends Country
{ 
  void showState(); 
} 
public class City implements State { 
public void showContinent()
{ 
    System.out.println("Asia"); 
} 
public void showCountry()
{ 
   System.out.println("India"); 
} 
public void showState()
{ 
   System.out.println("Jharkhand"); 
} 
void showCity()
{ 
   System.out.println("Dhanbad"); 
} 
public static void main(String[] args) 
{ 
   City c = new City(); 
   c.showContinent(); 
   c.showCountry(); 
   c.showState(); 
   c.showCity(); 
  } 
}
Output: 
       Asia 
       India 
       Jharkhand 
       Dhanbad

As you can observe that class City implements interface State. The interface State is inherited from interface Country and Country is inherited from interface Continent.

A class City also implements Country and Continent interfaces even though they are not explicitly included after the colon in the declaration of class City. The methods of all interfaces have been implemented in class City.

Multiple Inheritance in Java by Interface


When a class implements more than one interface, or an interface extends more than one interface, it is called multiple inheritance. Various forms of multiple inheritance are shown in the following figure.

Various forms multiple inheritance in Java by interface

Example: Multiple Inheritance Using Interfaces

Let’s write a Java program to achieve multiple inheritance using multiple interfaces.

package multipleInheritancebyInterfaces; 
public interface Home 
{ 
  void homeLoan(); 
} 
public interface Car 
{ 
  void carLoan(); 
} 
public interface Education 
{ 
  void educationLoan(); 
} 
public class Loan implements Home, Car, Education 
{ 
// Multiple inheritance using multiple interfaces. 
   public void homeLoan() 
   { 
      System.out.println("Rate of interest on home loan is 8.5%"); 
   } 
   public void carLoan()
   { 
      System.out.println("Rate of interest on car loan is 9.25%"); 
   } 
   public void educationLoan()
   { 
      System.out.println("Rate of interest on education loan is 10.45%"); 
   } 
public static void main(String[] args) 
{ 
    Loan l = new Loan(); 
    l.homeLoan(); 
    l.carLoan(); 
    l.educationLoan(); 
 } 
}
Output: 
       Rate of interest on home loan is 8.5% 
       Rate of interest on car loan is 9.25% 
       Rate of interest on education loan is 10.45%

The above program contains three interfaces, such as Home, Car, and Education. The class Loan inherits these three interfaces. Thus, we can achieve multiple inheritance in java through interfaces.

In Java, Multiple Inheritance is not supported through Class, but it is possible by Interface. Why?


As we have explained in the inheritance chapter, in multiple inheritance, subclasses are derived from multiple super classes. If two super classes have the same method name, then which method is inherited into subclass is the main confusion in multiple inheritance.

That’s why Java does not support multiple inheritance in the case of class. But, it is supported through an interface because there is no confusion. This is because its implementation is provided by the implementation class. Let’s understand it with the help of an example program.

Example: Resolving Method Conflict in Multiple Inheritance Using Interfaces

package multipleInheritancebyInterface; 
public interface AA 
{ 
  void m1(); 
} 
public interface BB 
{ 
  void m1(); 
} 
public class Myclass implements AA, BB 
{ 
  public void m1()
  { 
     System.out.println("Hello Java"); 
  } 
public static void main(String[] args) 
{ 
   Myclass mc = new Myclass(); 
    mc.m1(); 
  } 
}
Output: 
       Hello Java

As you can see in the above example, AA and BB interfaces have the same method name but there will be no confusion regarding which method is available to the implementation class.

Since both methods in interfaces have no body, and the body is provided in the implementation class, i.e. its implementation is provided by class Myclass. Thus, we can use methods of AA and BB interfaces without any confusion in a subclass.

Can We have an Interface without any Methods or Fields?


An interface without any fields or methods is called marker interface in Java. There are several built-in Java interfaces that have no method or field definitions. For example, Serializable, Cloneable, and Remote all are marker interfaces. They act as a form of communication among class objects.


Q. Why interface methods are public and abstract by default?

Ans: Interface methods are public and abstract by default because their implementation is left for third-party vendors.

Q. Suppose A is an interface. Can we create an object using new A()?

Ans: No, we cannot create an object of interface directly like this. This is because an interface does not provide method implementations, so the JVM cannot instantiate it. Instead, we create objects of the implementing classes.

Q. Suppose A is an interface. Can we declare a reference variable x of type A like this A x;?

Ans: Yes, we can declare a reference variable of type interface.


Recommended Java 8 Interface Tutorials