Java/J2EE and SOA (346 Blogs) Become a Certified Professional

What is Interface in Java and How to Implement it?

Last updated on Jun 17,2021 10.6K Views

Ravi Kiran
Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning... Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning more about Data Science and Big-Data Hadoop.

Java Interface is an advanced level of achieving abstraction in the Java Programming Language. Java interface helps in the reduction of complexity in the code and simplifies the readability. In this article, I will explain to you Java Interface through the following docket.

 

What is a Java Interface?

Computer Interface is known as a boundary which separates two or more systems. It exchanges data between the components in a system which could signals, commands or protocols.

java-interface

Java Abstraction provides the functionality of a particular method by hiding the implementation logic written inside the method. Similarly, Java Interface is also an Abstract Class which includes the Method Declaration but not its definition. A class implements an Interface to inherit the abstract methods. Along with abstract methods, an interface can also include constants, static methods, nested interfaces and default methods.

image

 

Similarities between a Class and an Interface.

An interface is completely similar to a normal class in Java. An interface includes the abstract methods and these methods are designed to be implemented. This process is merely equal to inheritance, which is normal when it comes to classes. We will discuss more on similarities.

  • Same as a class, an interface can also contain as many numbers of methods as required.
  • Similar to classes, the interface is also written with a .java extension file.
  • Surprisingly, the bytecode for an interface will have appeared in a .class file.
  • An interface is shown in the form of a package and their respective bytecode is in a directory that matches with the package name.

 

Why we need an Interface?

Java does not support Multiple Inheritances, due to which, It will not allow classes to extend more than one class at an instance. Child classes could not inherit the properties of multiple parent classes at a single instance, as it results in Diamond Problem. To overcome this issue, Interface is introduced. Let us understand this problem through an example.

 

diamond-problrm

 

Let us assume we have two planes, one can carry only passengers, the other one only cargo. Now, we need to inherit the properties of both the cargo plane and the passenger plane. Java would not support this solution as it ends up in ambiguity between the two planes.

diamond

But, if you can make it possible by making Java feel that it is inheriting one plane and implementing the methods present in the other plane. It is like a commercial Airplane which takes both passengers and cargo luggage. The Interface is like making a bigger plane which could do both the tasks without interfering with the components of one another, instead just borrowing the methods from the Interface Class.

 

inheritance

 

 

//Class A Code

package multiple;
class A{
     void msg(){System.out.println("Hello");}
}

//Class B Code

package multiple;
class B{
     void msg(){System.out.println("Welcome");}
}

Class C Code

package multiple;
class C extends A,B{ // This will not be accepted by Java, It will throw an error and code will not be executed.
public static void main(String args[]){
        C obj=new C();
        obj.msg();
        }
}

Output:

Error. This particular approach throws an exception. Java do not support Multiple inheritances. This error is known as Diamond Problem

Let us try a solution by using an interface, Child Classes can access the methods from Multiple Parent classes at a single instance.

//Interface Code

package MIS;
public interface solution {
public void Hello();
public void Welcome();
}

//Class Code

package MIS;
public class classA implements solution {
       public void Hello() {
            java.lang.System.out.println("Hello world");
       }
       public void Welcome() {
            java.lang.System.out.println("Welcome to Edureka");
}
public static void main(String[] args) {
       classA Edureka = new classA();
       Edureka.Hello();
       Edureka.Welcome();
       }
}

Output:

Hello World
Welcome to Edureka

Declaring a Java Interface: Syntax

interface interface_name {
// declare constant fields;
// declare methods();
//  default methods;
}

Let us go through an example on Java Interface

 

Java Interface Example

Let us create a simple Calculator based on Java Interface.

calci

 

//Interface Code

package basicoperations;
public interface maths {
public void add();
public void sub();
public void mul();
public void div();
}

//Class Code

package basicoperations;
import java.util.Scanner;
public class student1 implements maths {
        @Override
         public void add() {
         Scanner kb = new Scanner(System.in);
         System.out.println("Enter any two integer values to perform addition");
         int a=kb.nextInt();
         int b=kb.nextInt();
         int s=a+b;
         System.out.println("Sum of "+a+" and "+b+" is "+s);
   }
        @Override
         public void sub() {
         Scanner kb = new Scanner(System.in);
         System.out.println("Enter any two integer values to perform substraction");
         int a=kb.nextInt();
         int b=kb.nextInt();
         int s=a-b;
         System.out.println("Difference of "+a+" and "+b+" is "+s);
  }
        @Override
         public void mul() {
         Scanner kb = new Scanner(System.in);
         System.out.println("Enter any two integer values multiplication");
         int a=kb.nextInt();
         int b=kb.nextInt();
         int s=a*b;
         System.out.println("Product of "+a+" and "+b+" is "+s);
  }
        @Override
         public void div() {
         Scanner kb = new Scanner(System.in);
         System.out.println("Enter any two integer values division");
         int a=kb.nextInt();
         int b=kb.nextInt();
         int s=a/b;
         System.out.println("Quotient of "+a+" and "+b+" is "+s);
  }
public static void main(String[] args) {
   student1 Edureka1 = new student1();
   Edureka1.add();
   Edureka1.sub();
   Edureka1.mul();
   Edureka1.div();
   }
}

Output:

 

mathematics-java-interface

 

Advancing further, we will learn to nest a Java Interface.

 

Nesting the Java Interface

Interface Nesting is a process of declaring an Interface inside another Existing Interface or declaring an Interface inside a Class. The Nested Interface is also known as an Inner Interface.

The Nested Interface cannot be accessed directly. Hence, Nesting is implemented in order to resolve the Namespaces by grouping them with their related Interfaces and Classes. By this procedure, we can call the Nested Interface through the Outer Class or Outer Interface name followed by a dot( . ), and Interface name.

Let us try some examples based on Interface Nesting. First, let us try to nest a Java Interface inside another Java Interface as shown below:

//Interface Code

package Nest;
public interface OuterInterface {
     void display();
     interface InnerInterface{
           void InnerMethod();
       }
}

//Class Code

package Nest;
class NestedInterfaceDemo
implements OuterInterface.InnerInterface{
public void InnerMethod(){
   int n = 10, t1 = 0, t2 = 1;
   System.out.print("First " + n + " terms: ");
         for (int i = 1; i <= n; ++i)
        {
             System.out.print(t1 + " + ");
             int sum = t1 + t2;
             t1 = t2;
             t2 = sum;
        }
        System.out.println("nPrinting from Nested InnerInterface method...!n");
    }
public static void main(String args[]){
       OuterInterface.InnerInterface obj=new NestedInterfaceDemo();
       obj.InnerMethod();
    }
}

Output:

First 10 terms: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +
Printing from Nested InnerInterface method...!

 

Now, Let us try to nest a Java Interface inside a Java Class.

//Interface Code

package Nest2;
public class EdurekaClass {
       interface EdurekaInterface{
              void NestedMethod();
        }
}

//Class Code

package Nest2;
class NestedInterfaceDemo2 implements EdurekaClass.EdurekaInterface{
public void NestedMethod(){
            String input = "Edureka";
            byte [] strAsByteArray = input.getBytes();
            byte [] result = new byte [strAsByteArray.length];
            for (int i = 0; i<strAsByteArray.length; i++)
                    result[i] = strAsByteArray[strAsByteArray.length-i-1];
                    System.out.println(new String(result));
            }
public static void main(String args[]){
          EdurekaClass.EdurekaInterface obj = new NestedInterfaceDemo2();
          obj.NestedMethod();
     }
}

Output:

akerudE

Although an Interface looks almost similar to a Class, there are some differences between them, Let us discuss their differences.

 

Difference between Java Class and Java Interface

 

INTERFACECLASS
Supports Multiple InheritanceDoes not support Multiple Inheritance
Does not have Data MembersIncludes Data Members
Does not have ConstructorsIncludes Constructors
Includes Incomplete Members(Signature Member)Includes both Complete(Abstract) and Incomplete members
Does not have Access ModifiersIncludes Access Modifiers
The interface does not have Static MembersThe class has all its members as Static

 

Advantages and Disadvantages of Java Interface

Advantages:

  • Java Interface supports Multiple Inheritance.
  • Java Interface enables programmers to break up the complex programming approaches and simplify the dependencies between the objects.
  • Java Interface makes the data members and methods in an application to be loosely coupled.

Disadvantages:

  • Use of Java Interface brings down the execution speed of the application.
  • Java Interfaces in the application are either used repeatedly at large extent or hardly used at all.

 

Key Points on Java Interface

  • None of the methods declared in the interface has a body that makes it provide complete abstraction.
  • It is not possible to create an object of an interface. Hence, the Instantiation of an Interface is not possible.
  • A Class can implement an interface by using the keyword implements. Let us see this through an example.

//Interface Code

package extInterface;
public interface extInterface {
        public void method1();
        public void method2();
}

//Class Code

package extInterface;
import java.util.Scanner;
class Edureka implements extInterface{
    public void method1(){
         System.out.println("implementation of method1");
         Scanner scanner = new Scanner(System.in);
         System.out.println("Enter number to find square root in Java : ");
         double square = scanner.nextDouble();
         double squareRoot = Math.sqrt(square);
         System.out.printf("Square root of number: %f is : %f %n" , square, squareRoot);
    }
    public void method2(){
               System.out.println("implementation of method2");
        }
public static void main(String arg[]){
               extInterface obj = new Edureka();
               obj.method1();
       }
}

Output:

implementation of method1
Enter number to find square root in Java :
16
Square root of number: 16.0 is : 4.0
  • A Class can implement multiple inheritances at a single instance. Let us understand it through the following code.

//Interface 1 Code

package ExtendInt;
public interface Interface1 {
       public void armstrong();
}

//Interface 2 Code

package ExtendInt;
public interface Interface2 {
           public void prime();
}
//Class Code
package ExtendInt;
public class Edureka2 implements Interface1,Interface2{
          public void armstrong(){
                 int c=0,a,temp;
                 int n=153;// input 
                 temp=n;
                 while(n>0){
                        a=n%10;
                        n=n/10;
                        c=c+(a*a*a);
                 }
                  if(temp==c)
                          System.out.println("armstrong number");
                  else
                          System.out.println("Not armstrong number");
                          System.out.println("Extending to Interface 1");
          }
          public void prime(){
          int i,m=0,flag=0;
          int n=3;// input 
          m=n/2;
          if(n==0||n==1){
                  System.out.println(n+" is not prime number");
          }
          else{
                  for(i=2;i<=m;i++){
                        if(n%i==0){
                                System.out.println(n+" is not prime number");
                                flag=1;
                                break;
                        }
                  }
                  if(flag==0) { 
                  System.out.println(n+" is prime number"); 
                  }
          }
          System.out.println("Extending to Interface 2");
          }
public static void main(String args[]){
               Interface2 obj = new Edureka2();
               obj.prime();
               Interface1 obj1 = new Edureka2();
               obj1.armstrong();
         }
}

Output:

3 is prime number
Extending to Interface 2
armstrong number
Extending to Interface 1

 

  • Java Interface requires the variables declared to be initialized at the time of declaration.
  • Access Modifiers for an interface are set to public static and final by default. Let us understand this by an example

//Interface Code

package test;
public interface Try {
       //public int a=10;
       //public static final int a=10;
       //static int a=0;
       //final int a=10;
       //int a=10;
}
  • All the above declarations are true and valid inside an Interface.
  • Java Interface is capable to extend any number of Interfaces, but can never implement one.
  • A Java class can implement any number of Interfaces.
  • Java Class cannot implement Interfaces with the same method name and different return type.
  • If there are two or more methods with the same method name, are existing in multiple interfaces, then implementing the method for once is enough. Let us understand this with a practical example.

//Interface Code

package same;
public interface A {
        public void display();
}
//Interface Code
package same;
public interface B {
        public void display();
}
//Class Code
package same;
class same implements A,B {
           public void display() {
                   System.out.println("displaying data");
           }
     public static void main(String[] args) {
           same print = new same();
           print.display();
     }
}

Output:

Welcome to Edureka E-Learning

With this, we come to an end of this article. I hope you have understood the importance of Interface, Syntax, functionality, Interface Nesting, Key points of Java Interface and operations performed using them.

Now that you have understood basics of Java, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Mention it in the comments section of this “Java Interface” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDate
Java Certification Training Course

Class Starts on 28th January,2023

28th January

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th February,2023

25th February

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is Interface in Java and How to Implement it?

edureka.co