Full Stack Web Development Internship Program
- 5k Enrolled Learners
- Weekend/Weekday
- Live Class
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.
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 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.
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.
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.
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.
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.
//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
interface interface_name { // declare constant fields; // declare methods(); // default methods; }
Let us go through an example on Java Interface
Let us create a simple Calculator based on Java Interface.
//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:
Advancing further, we will learn to nest a 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.
Advantages:
Disadvantages:
//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
//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
//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; }
//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.
Course Name | Date | |
---|---|---|
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 |
edureka.co