July 9, 2022

Interface in Java With Examples

Interface in Java helps to fully abstract the implementation of the class. Interfaces act as a contract for the class, detailing what methods can be invoked by any outside entity without actually providing what methods should do. The class implementing an interface has to provide the behavior (implement the methods defined in interface).

How is interface created in Java

An interface in Java is created by using the interface keyword. All fields in an interface are automatically public, static, and final. Methods in an interface have no body (only method signature), are public and abstract by default.

Note that Java 8 onward interfaces can have default methods and static methods and Java 9 onward private methods in interface are also permitted. In this post we’ll discuss interfaces in its normal and original form.

Syntax of interface in Java

access_modifier interface Interface_Name{
  type var1 = value;
  type var2 = value;

  return_type methodName1(arguments);
  return_type methodName2(arguments);

  ..
  ..
}

Valid access modifiers for interface are default access (if no access modifier is specified) and public. Default means interface is available only in the package where it is created, public means it can be accessed from all the other packages too.

Note that the method signatures are terminated with a semicolon, there is no implementation.

Creating and implementing an interface in Java

In this Java example there is an interface Payment with one method doPayment(double amount) which is implemented by two classes CashPayment and CCPayment.

public interface Payment {
  void doPayment(double amount);
}
Implementing classes

To use an interface, you write a class that implements the interface. A class implementing an interface in Java must implement all methods defined by that interface before the class successfully compiles. If class is not implementing all the methods of the interface then it should be declared as an abstract class.

public class CashPayment implements Payment {
  @Override
  public void doPayment(double amount) {
    System.out.println("Cash payment of amount- " + amount);
  }
}

public class CCPayment implements Payment {
  @Override
  public void doPayment(double amount) {
    System.out.println("Swipe credit card for amount- " + amount);
  }
}

As you can see here one interface is defined which just declares a method, leaving the method implementation to the classes that implement this interface. A class implementing an interface must include implements keyword in the class definition.

Features of interface in Java

Let’s go through some of the important points about interfaces in Java using the above example as reference.

  1. Interfaces in Java can’t have instance variables, only public, static, final constants. For example trying to add an instance variable in the Payment interface as- public String name; results in compile time error “The blank final field name may not have been initialized”.
  2. An interface in Java can’t be instantiated. Trying to create an instance of Payment interface like this- Payment payment = new Payment(); results in compile time error “Cannot instantiate the type Payment”.
  3. Since interfaces can’t be instantiated so interfaces in Java can’t have constructors.
  4. Though interface can’t be instantiated but an object reference of interface can be created. This object reference can refer to the instance of any class that implements this interface. That’s how interface in Java helps in achieving run time polymorphism. In the above example you can see that the reference of the interface Payment is created- Payment payment; which refers to the implementing class objects and call the appropriate doPayment() method. Method that has to be executed is looked up dynamically at run time.
  5. A class can implement more than one interfaces, that’s the only way you can have multiple inheritance in Java. Java doesn’t allow multiple inheritance in case of classes so you can’t extend more than one class in Java.
  6. Interfaces are separated by a comma when a class implements more than one interfaces.
    class class_name implements interface 1, interface 2{
       ..
       ..
    }
    

Interface extends another interface

A class implements an interface but an interface extends another interface in Java using the extends keyword. An interface can extend more than one interfaces.

When a class implements an interface that has inherited another interface then the class must implement all the methods in all those interfaces.

Java example
interface A{
  int add(int a, int b);
}

interface B extends A{
  int subtract(int a, int b);
}

public class MainClass implements B{
  @Override
  public int subtract(int a, int b) {
    return (a-b);
  }

  @Override
  public int add(int a, int b) {
    return (a+b);
  }
}

Nested interfaces in Java

A nested interface is an interface that is declared as a member of a class or another interface. Nested interface can have public, private, protected or default access and it must be qualified by a class name or interface in which it is declared when used.

class A{
  //nested interface
  interface MyInterface{
    int add(int a, int b);
  }
}

// Class implementing nested interface
class B implements A.MyInterface {
  @Override
  public int add(int a, int b) {
    return a+b;
  }
}

public class MainClass {
  public static void main(String[] args) {
    // Reference to nested interface
    A.MyInterface refObj = new B();
    int result = refObj.add(5, 6);
    System.out.println("Result- " + result);
  }
}
Output
Result- 11
That's all for the topic Interface in Java With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like

No comments:

Post a Comment