Interface in Java with Example

An interface in Java is syntactically similar to a class but can have only abstract methods declaration and constants as members.

In other words, an interface is a collection of abstract methods and constants (i.e. static and final fields). It is used to achieve complete abstraction.

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 Interface?


There are mainly five reasons or purposes of using an interface in Java. They are as follows:

1. In industry, architect-level people create interfaces, and then they are given to developers for writing classes by implementing interfaces provided.

2. Using interfaces is the best way to expose our project’s API to some other projects. In other words, we can provide interface methods to the third-party vendors for their implementation.

For example, HDFC bank can expose methods or interfaces to various shopping carts.

3. Programmers use interface to customize features of software differently for different objects.

4. It is used to achieve full abstraction in java.

5. By using interfaces, we can achieve the functionality of multiple inheritance.

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 name. It has the following general form:

Syntax:
   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.
How to declare Interface in Java
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.


Note:

a) Earlier to Java 8, an interface could not define any implementation whatsoever. An interface can only declare abstract methods.

b) Java 8 changed this rule. From Java 8 onwards, it is also possible to add a default implementation to an interface method.

c) To support lambda functions, Java 8 has added a new feature to interface. We can also declare default methods and static methods inside interfaces.

d) From Java 9 onwards, an interface can also declare private methods.

Features of Interface


There are the following features of an interface in Java. They are as follows:

1. Interface provides pure abstraction in Java. It also represents the Is-A relationship.

2. It can contain three types of methods: abstract, default, and static methods.

3. All the (non-default) methods declared in the interface are by default abstract and public. So, there is no need to write abstract or public modifiers before them.

4. 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.

5. Interface cannot have constructors.

6. The interface is the only mechanism that allows achieving multiple inheritance in java.

7. A Java class can implement any number of interfaces by using keyword implements.

8. 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. But we can create a reference to an interface that can point to an object of any of its derived types implementing it.

2. An interface may not be declared with final keyword.

3. It cannot have instance variables. If we 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. We cannot reduce the visibility of an interface method while overriding. That is, when we implement an interface method, it must be declared as public.

6. It 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. 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:

Syntax:
  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

Let’s understand the extending interface better with the help of different examples.

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:

Syntax:
1. accessModifier class className implements interfaceName 
   {
    // method implementations;
    // member declaration of class;
   }
2. 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:

1. 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.
2. Class extends class implements interface.
3. 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 implementing interface in Java

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


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

Program code 1:

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

2. Let’s take an example program where class B implements an interface A.

Program code 2:

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


Let’s take an example program where multiple classes implement the same 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. This 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.

Program code 3:

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.

Program code 4:

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
Let’s write a Java program to achieve multiple inheritance using multiple interfaces.

Program code 5:

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 superclasses.

If two superclasses 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.

Program code 6:

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 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.

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

Ans: Yes.


Recommended Java 8 Interface Tutorials


In this tutorial, we have explained almost all important topics related to interface in Java with the help of example programs. Hope that you will have understood the basic concept of interface nicely and enjoyed its programming. In the next, we will learn the use of interface in the real-time application
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love