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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...