Interface in java

Let’s learn interface in java.

Interface in java

interface in java

Java interface is a collection of abstract methods, static methods, default methods and constants. These abstract methods have only declaration with no definition.

Also read – learn abstraction in java

A class which implements interface should define each and every method in the class. Interface is used to implement multiple inheritance in java.

Now let’s learn interface in java with example program.


Syntax

interface
{
   // fields are static, final and public
   // methods are implicitly abstract and public
}



Implementing interface in java

To implement interface ‘implements’ keyword is used. In the below example interface Vehicle has abstract method accelerate() and we can see implementation of accelerate() method in class Audi and class BMW.

interface Vehicle
{ 
   public void accelerate(); 
}

class BMW implements Vehicle
{ 
   public void accelerate()
   {
      System.out.println("BMW accelerating...");
   } 
}

public class InterfaceDemo 
{
   public static void main(String[] args) 
   {
      Vehicle obj = new Audi();
      obj.accelerate();
   }
}



Output:

BMW accelerating…

In the above example we have declared interface Vehicle and we can see the implementation in the class BMW.

The relationship between a class and interface is a class implements an interface, an interface extends interface and a class extends another class.

NOTE:

  • A class can extend many interfaces. But can extend only one class.

Why multiple inheritance is not supported in java?

Does java support multiple inheritance? The answer is NO.

class X
{
   public void print()
   {
      System.out.println("class X method");
   }
}

class Y
{
   public void print()
   {
      System.out.println("class Y method");
   }
}

class Demo extends X, Y
{
   public static void main(String args[])
   {
      Demo obj = new Demo();
      obj.print();
   }
}



The reason is, in java you cannot extend two classes. In the above example class X and class Y has method print() with the same name.

Also read – inheritance in java

class Demo is extending both class X and Y. Here compiler have ambiguity to call print() method of class X or class Y.

So to solve this ambiguity, java does not allow multiple inheritance in java. But java supports multiple inheritance in java with the help of interfaces.


Difference between class and interface in java

  • Class does not support multiple inheritance whereas interface support multiple inheritance.
  • Classes have data members whereas interfaces do not have data members.
  • Class do have constructors whereas interface do not have constructors.
  • Class have incomplete and complete method whereas interface have incomplete methods.
  • Class can have public, private, default and protected access modifiers whereas interface can have only “public” as default access modifier.
  • Class can have static members whereas interface cannot have members as static.

Multiple inheritance using interface in java

A class implementing more than one interface or interface extending more than one interface is multiple inheritance in java.

interface X
{ 
   void display(); 
}
interface Y
{ 
   void print(); 
}
class TestInterface implements X, Y
{ 
   public void display()
   {
      System.out.println("Hello World!!");
   }

   public void print()
   {
      System.out.println("Interface example");
   }
   public static void main(String[] args) 
   {
      TestInterface test = new TestInterface(); 
      test.display(); 
      test.print();
   }
}



Output:

Hello World!!
Interface example


Extending interfaces in java

‘extends’ keyword is used to extend interface. Unlike class which extend only one class interface can extend more than one interface.

Syntax:

accessmodifier interface InterfaceName extends interface1, interface2
{
   // body of interface
}

Example:
public interface Car extends Audi, BMW, Mercedes
{
   // body of interface Car
}



Let’s see an example on extending interface in java,

interface Person
{
   public void division();
   public void employeeRole();
}

interface TeamLeader extends Person
{
   public void javaTeamLead();
}

interface Manager extends Person, TeamLeader
{
   public void javaDivision();
}

public class ExtendingInterfaceExample implements Manager
{
   public static void main(String[] args) 
   {
      ExtendingInterfaceExample obj = new ExtendingInterfaceExample();
      obj.division();
      obj.employeeRole();
      obj.javaTeamLead();
      obj.javaDivision();
   }

   public void division()
   {
      System.out.println("software");
   }

   public void employeeRole()
   {
      System.out.println("software engineer");
   }

   public void javaTeamLead()
   {
      System.out.println("Java Team Leader");
   }

   public void javaDivision()
   {
      System.out.println("Manager java division");
   }
}



Output:

software
software engineer
Java Team Leader
Manager java division


Nested interface in java

Java nested interface is nothing but an interface declared within another interface. Like nested classes interface can also be nested.

By nesting interfaces we can group similar interfaces in one place and helps in maintaining java code.

Like nested class, nested interface can be accessed by outer interface and cannot be accessed directly.

NOTE:

  • nested interfaces are static implicitly.
  • nested interfaces should be public when it is inside an interface.

Syntax:

interface interfaceName
{
   // abstract methods
   interface nestedinterfacename
   {
      // abstract methods
   }
}

// nested interface inside a class
class demo
{
   interface nestedinterfacename
   {
      // abstract methods
   }
}



Let’s see nested interface declared within an interface example,

public interface Demo 
{
   void print();
   // nested interface
   interface inner
   {
      void displayPrimeNumber();
   }
}


class InterfaceDemo implements Demo.inner
{
   public void displayPrimeNumber()
   {
      int a = 0;
      int number = 0;
      String strPrimeNumber = "";
      for(a = 1; a <= 100; a++)
      {
         int counter = 0;
         for(number = a; number >= 1; number--)
         {
            if(a % number == 0)
            {
               counter = counter + 1;
            }
         }
         if(counter == 2)
         {
            strPrimeNumber = strPrimeNumber + a + " ";
         }
      }
      System.out.println("Prime numbers from 1 to 100 : ");
      System.out.println(strPrimeNumber);
   }

   public static void main(String[] args) 
   {
      // upcasting
      Demo.inner obj = new InterfaceDemo();
      obj.displayPrimeNumber();
   }
}



Output:

Prime numbers from 1 to 100 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Now let’s see another example where nested interface declared inside a class.

class Demo
{
   interface print
   {
      void helloWorld();
   }
}

class NestedInterfaceExample implements Demo.print
{
   public void helloWorld()
   {
      System.out.println("nested interface method");
   }
   
   public static void main(String[] args)
   {
      Demo.print obj = new NestedInterfaceExample();
      obj.helloWorld();
   }
}



Output:

nested interface method


Java 8 default method and static method

Before Java 8, interface had methods with no definition. But in Java 8 it can have default methods and static methods.

By this new feature java developers can add new methods in interface without affecting class that implements these interfaces.

interface Vehicle
{
   // default method
   default void display()
   {
      System.out.println("In Default method");
   }
   // existing abstract method
   void helloWorld();
}

class BMW implements Vehicle
{
   public void helloWorld()
   {
      System.out.println("Hello World Java");
   }
   public static void main(String[] args) 
   {
      BMW obj = new BMW();
      obj.display();
      obj.helloWorld();
   }
}



Output:

In Default method

Hello World Java


Java 8 Static method

In Java 8 there is a new feature called static methods which is similar to default methods except we cannot override static method in implementation class.

NOTE: Static methods are static cannot be overridden.

Let’s see a java program to demonstrate static methods in java 8,

public interface Vehicle
{
   // default method
   default void display()
   {
      System.out.println("In Default method");
   }

   // static method java8
   static void print()
   {
      System.out.println("in java8 static method");
   }

   // existing abstract method
   void helloWorld();
}

public class StaticMethodJava8 implements Vehicle
{
   public void helloWorld()
   {
      System.out.println("Hello World Java");
   }

   public static void main(String[] args) 
   {
      StaticMethodJava8 obj = new StaticMethodJava8();
      // call default method
      obj.display();
      // call static method java8
      Vehicle.print();
      // call existing abstract method
      obj.helloWorld();
   }
}



Output:

In Default method
in java8 static method
Hello World Java


Difference between abstract class and interface in java

abstract classinterface
have instance methods which implements default beahviour.methods are implicitly abstract. No implementation.
may have non final variables.variables declared is final by default.
members are protected, private etc.members are public by default.
abstract class “extends”.interface “implements”.
abstract class can extend another class and implement more than one interfaces.interface can only extend another interface.
class can extend only one abstract classclass can implement multiple interfaces.
cannot be instantiated. can be invoked in main() method.cannot be instantiated, abstract.

use of interface in java

  • to achieve loose coupling
  • to achieve abstraction
  • supports multiple inheritance

Summary

In java programming,

  • Interface provide full abstraction.
  • Class overrides all abstract methods declared in interface.
  • All Interface methods are public and abstract by default.
  • Interface can contain only method signatures, constants, default methods, nested types and static methods.
  • Interfaces cannot be instantiated. We cannot create object of an interface.
  • Interfaces can only be implemented by class or extended by other interface.
  • Variables declared in interface are final by default.
  • A class can’t implement two interfaces that have methods with same name.
  • In Java 8, interface can have static methods and default methods.