Skip to main content

Interface in Java with examples

Interface in Java with examples

In java there is another way for achieve Abstraction, That is using Interface.

What is Interface in Java?

Interface is like java class, but interface has only abstract method and static constants.
Interface is used for implement multiple inheritance. multiple inheritance is not supported in java.
In simple word Interface is used to achieve multiple inheritance and abstraction.


All method in interface are public and abstract. Interface only contains abstract method means method does not contain its body.
A java class can implement multiple interface.

Syntax of Interface
Interface interface_name {
   
    // Constants variables.
    // Method declaration without body.

}

Like abstraction, Interface also does not have method body. But interface contains method declaration, Default, Constants and Static methods.
Interface is implements by class and then class provides implementation of abstract methods.
Interface can also extends another interface like class extends class.

In java we can not extends more than one class means that multiple inheritance does not supported in java.
So one major advantage of interface is that we can implements more than one interface and extends one class.
Like in following example.

InterfaceOne.java
public interface InterfaceOne {
    // Abstract method
}

InterfaceTwo.java
public interface InterfaceTwo extends InterfaceOne{
      // Abstract method
}

ClassOne.java
public class ClassOne{

    public static void main(String[] args) {
        // method body
   
    }
}

InterfaceImplClass.java
public class InterfaceImplClass extends ClassOne implements InterfaceOne, InterfaceTwo{

    public static void main(String[] args) {
        // Implementation of Interfaces
   
    }
}

In above example we extends one class and implements two interface. we have to implement all InterfaceOne and InterfaceTwo methods in InterfaceImplClass.
If you don't want to implement those method in InterfaceImplClass then you have to make InterfaceImplClass class to abstract. means add abstract keyword after class so it is also make abstract.

Lets see simple example of interface so you can understand better.

InterfaceOne.java
public interface InterfaceOne {
    
    // Abstract Method
    public void methodOne();
   
}

InterfaceImplClass.java
public class InterfaceImplClass implements InterfaceOne{

    public static void main(String[] args) {

        // Created object and call methodOne
        InterfaceImplClass obj = new InterfaceImplClass();
        obj.methodOne();
    }

    @Override
    public void methodOne() {
        // Implemetation of InterfaceOne
        System.out.println("Implementation of Interface One");
    }

}

Output :-
Implementation of Interface One

In java, interface can not implements interface only class can implements.
but, interface can extends another interface like class extends class.
lets see following example.

InterfaceOne.java
interface InterfaceOne{
    public void method1();
}

InterfaceTwo.java
interface InterfaceTwo extends InterfaceOne {
    public void method2();
}

ImplClass.java
public class ImplClass  implements InterfaceTwo{
 
    @Override
    public void method1(){
        System.out.println("InterfaceOne method");
    }
   

     @Override
     public void method2(){
        System.out.println("InterfaceTwo method");
    }

    public static void main(String args[]){
        InterfaceTwo obj = new
ImplClass();
           
            obj.method1();
            obj.method2();
     
    }
}

Output :-
InterfaceOne method
InterfaceTwo method

Nested Interface in Java
There is also nested interface like nested class.
Nested interface means one interface inside another existing interface. We can not access directly nested interface.

Lets see example how nested interface works.


OuterInterface.java
public interface OuterInterface{

     void outerMethod();

    // Inner Interface
     interface InnerInterface{
           void InnerMethod();

       }   
}


InterfaceImplClass.java
public class InterfaceImplClass implements OuterInterface, OuterInterface.InnerInterface{

    public static void main(String[] args) {
       
        // Creating object
        InterfaceImplClass obj = new InterfaceImplClass();
        // Calling inner method of inner interface
        obj.InnerMethod();
        // Calling outer method of outer interface
        obj.outerMethod();
    }

    @Override
    public void InnerMethod() {
        System.out.println("Inner method");
    }

    @Override
    public void
outerMethod() {
        System.out.println("Outer method");
    }

}

Output :-
Inner method
Outer method

We can access inner interface using .(dot) with outer interface like in above example.
we implements InterfaceOne.InnerInterface using .(dot). and we can implements inner method of inner interface.
If we want to access outer interface then we have to implement OuterInterface also like in above example otherwise we can not implements outer interface methods.

We can also use inner interface in Class. lets see example of that.

ClassOne.java
public class ClassOne{

    // Inner Interface
    interface innerInterface {
        void innerInterfaceMethod();
    } 
}

ClassTwo.java
public class ClassTwo implements ClassOne.innerInterface{

    public static void main(String[] args) {
        // Object creation
        ClassTwo obj = new ClassTwo ();
        // Calling inner method of implementation interface.
        obj.innerInterfaceMethod();

    }

    @Override
    public void innerInterfaceMethod() {
        System.out.println("Implementation of inner interface in class");
       
    }
}

Output :-
Implementation of inner interface in class

So we can declare inner interface in class and access implement that inner interface using ClassName.InnerInterfaceName.

Lets see example of how we can use Static and Default method in interface.

InterfaceDemo.java
public interface InterfaceDemo {
   
    // Static method   
    static int squareOfMethod(int number) {
        return number * number;
    } 
   
    // Default method
    default int cubeOfMethod(int number) {
        return number * number * number;
    } 
   
}

InterfaceImplClass.java
public class InterfaceImplClass implements InterfaceDemo {
    public static void main(String[] args) {

        // Creating object of InterfaceImplClass
        InterfaceDemo obj = new InterfaceImplClass();
       
        // Calling Default method
        System.out.println("Square of 2 is :- " + InterfaceDemo.squareOfMethod(2));
        // Calling Static method
        System.out.println("Cube of 2 is :- " + obj.cubeOfMethod(2));
       
    }
}

Output :-
Square of 2 is :- 4
Cube of 2 is :- 8

We can call static method directly using ClassName.StaticMethod like in above example.

Advantages of Interface
  • Using interface we can implement multiple inheritance in java.
  • Using interface we can implements more than one interface, but in class we can only one.
  • Interface makes our application loosely coupled.
  • Interface function breaks up complex design.
Other related blog.
If you want to learn coding for FREE follow this link :-

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...