Interface in Java


An interface in Java is a mechanism which is used to achieve completely abstraction. It is basically a kind of class but can have only abstract method declarations and constants as members. In other words, an interface in Java is a collection of abstract methods and constants (i.e, final fields).
Every interface is by default abstract. So, It is not compulsory to write abstract keyword with the interface. We cannot instantiate an interface just like an abstract class but we can create a reference variable.

Why Use Java Interface?


There are mainly five reasons to use the interface. They are as follows:
1. In industry, architect level people create interfaces and then it is given to developers for writing classes by implementing interfaces provided.
2. Using interfaces is the best way to expose our projects API to some other project. 
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 fully abstraction.
5. By using interface, we can achieve the functionality of multiple inheritance.

How to Declare Interface in Java?


In Java, an interface is declared much like a class. It is declared by using the keyword interface followed by the 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 also specify access modifiers such as public, protected, private, etc.
For example:
     public interface MyInterface {
       int x=10; // For simplicity, Integer constant are used.
       int y=20:
       void m1(); // public and abstract keyword invisibly present.
       void m2();
   }

As you can see in above example, both methods m1() and m2() in an interface are declared with no body and does not have public or abstract modifiers present. The variables x and y declared in MyInterface are like simple variables. The compiler automatically adds public and abstract keyword before to all interface methods. Moreover, it also adds public, static and final keywords before interface variables. It can be shown in the below figure.
Declaration of Interface variables and methods 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. 
Key points: 
1. The value of interface variables must be initialized when it is declared. Since it is defined as final.
2. A class that implements an interface, must provide implementations of all the methods defined in the interface.
3. We cannot reduce the visibility of an interface method while overriding.

Features of Interface in Java


There are following features of the interface in Java. They are as follows:
1. Interface provides pure abstraction in java. It also represents the Is-A relationship.
2. We cannot create an object of interface in Java.
3. All the methods declared in 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 constructor.
6. It can be compiled but cannot run.

7. The interface is the only mechanism which allows achieving multiple inheritance in java. 
8. A Java class can implement any number of interfaces by using keyword implements. 
9. Interface can extend an interface and can also extend multiple interfaces.
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 Interfaces in Java


Like classes, Interface can also extend another interface. That means an interface can be subinterfaces from other interfaces. The new subinterface will inherit all members of the superinterface similar to subclasses. It can be done by using a keyword "extends". It has the following general form:
   interface interfaceName2 extends interfaceName1 {
       // body of interfaceName2.
    }
Extending interface in java
For example:
You can define all the constants into one interface and methods in other. You can use constants in classes where methods are not required.
    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.
You can also add various interfaces together into a single interface by the following declaration. 
    interface A { int x=20; int y=30; } interface B extends A { void show(); } interface C extends A, B { . . . . . . . . }
Key point: 
1. An interface cannot extend classes because it would violate rule that an interface can have only abstract method and constants.
2. An interface can extend Interface1, Interface2.

Implementing Interface in Java


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 interface and all its superinterfaces. Otherwise, the class must be declared as abstract. The syntax of interface implementation using a class is shown below.
Syntax: 
  1.  accessModifier class className implements interfaceName {
          // method implementations;
          // member declaration of class;
         }
The access modifiers can be public, private, and protected.
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 below figure. 
Implementing interface in java

Accessing Interface Variables 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. The values can also be used in any method as part of the variable declaration or anywhere in the class.
Let's see various example programs related to all important points.

Java Interface Example Programs


Program source code 1: Let's create a 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
Program source code 2: Let's create a program where class B implements an interface A.
    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(); // a.show(); // Compile-time error because a reference of interface can only call methods declared in it and implemented by implementing class. show() method is not part of interface. It is the 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 Interfaces


Program source code 3: Let's create a 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 interfaces. In the above figure, (d) shows polymorphism in interfaces where class B and class C implement the same interface A. Let's see an example program.


    package interfacePrograms; public interface Area { float pi=3.14f; // Constant declaration. float calculateArea(float x, float y); } public class Circle implements Area { public float calculateArea(float x, float y){ float areaOfCircle=pi*x*y; // Implementation. return areaOfCircle; } } public class Square implements Area { public float calculateArea(float x, float y){ float areaOfSquare=x*y; // Implementation. return areaOfSquare; } } public class InterfaceTest { public static void main(String[] args) { Area a; // Creating interface reference. a=new Circle(); // Creating object of circle. float circle=a.calculateArea(20, 10.5f); System.out.println("Area of circle: " +circle); a=new Square(); // Creating object of square. float square=a.calculateArea(20.5f, 10.5f); System.out.println("Area of square: " +square); } }
    Output: Area of circle: 659.4 Area of square: 215.25

Multilevel Inheritance by Interface


Program source code 4: Let's make a program where we will create a multilevel inheritance by interface. One interface extends an interface, that interface extends another interface, and a class implements methods of all interfaces, we can achieve multilevel inheritance by interface.
    package interfacePrograms; public interface Continent { void showContinent(); } public interface Country { void showCountry(); } public interface State { 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, 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 interfaces, or an interface extends more than one interfaces, it is called multiple inheritance. Various forms of multiple inheritance are shown in the following figure.
Multiple inheritance in java by interface
Program source code 5: Let's create a 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 an 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 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 a suitable example program.
Program source 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 interface 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.

Java 8 Default method in Interface


Since Java 1.8 or above, Default methods are allowed where we can have method body in interface. But we will need to make it default method. Let's see an example program related to it.
Program source code 7: Let's create a program where we will declare a default method with a body in interface.
    package interfacePrograms; public interface AA { void m1(); default void m2(){ System.out.println("default method"); } } public class BB implements AA { public void m1(){ System.out.println("m1-AA"); } public static void main(String[] args) { AA obj=new BB(); obj.m1(); obj.m2(); } }
    Output: m1-AA default method

Java 8 Static Method in Interface 


Since Java 1.8 or above, static methods are allowed in interface. Let's see an example.
Program source code 8: 
    package interfacePrograms; public interface Perimeter { void msg(); static int peri(int l, int b){ return 2*(l+b); } } public class Rectangle implements Perimeter { public void msg(){ System.out.println("Perimeter of rectangle"); } public static void main(String[] args) { Perimeter p=new Rectangle(); p.msg(); int perimeter=Perimeter.peri(20,30); System.out.println(perimeter); } }
    Output: Perimeter of rectangle 100

Can We have an Interface without any Methods or Fields?


An interface without any fields or methods is called marker interface. 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. 

Final words 
Hope that this tutorial has covered almost all important points related to interface in java with example programs. I hope that you will have enjoyed this tutorial.

Thanks for reading.