Java Interface is similar to a class capable of handling multiple inheritance. However, Java Interfaces do not have a body; the class must implement them before you can access them.
Why use the interface in Java
The class that implements the interface must implement all the methods of that interface. Also, the Java programming language does not allow you to extend more than one class. However, you can implement more than one interface in your class.
Java Interface
Java Interface is a collection of abstract methods. An interface can have methods and variables just like the Java class, but the difference is that the methods declared in the interface are, by default, abstract. Likewise, the variables declared in an interface are public, static & final by default, too.
In class, multiple inheritance is not possible. To remove this disadvantage, we use an interface capable of handling multiple inheritance.
How to declare an interface in Java
To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in the interface are declared with an empty body, and all the fields are public, static, and final by default.
A class that implements an interface must implement all the methods declared in the interface. If we want to implement an interface, we must use the implements keyword.
Some important points about Interface
- It is a reference type in Java.
- It has methods, and by default, they are abstract.
- The data types are public, static, and final in an Interface.
- We cannot create an object for an interface, i.e., not instantiated.
- The interface does not have a constructor.
- Whenever a class wants to implement any interface, that class needs to use the “implements” keyword instead of “extends.”
- An interface cannot implement another Interface. It has to extend another interface if needed.
- An interface declared inside another interface is referred to as a nested interface.
- At the time of declaration, the interface variable must be initialized. Otherwise, the compiler will throw an error.
- The class cannot implement two Java interfaces with methods with the same name but different return types.
Difference between Class and Interface
In class, you can instantiate the variable and create an object. | In an interface, you can’t instantiate variables and create an object. |
Class can contain concrete(with implementation) methods. | The interface cannot contain concrete(with implementation) methods. |
The access specifiers used with classes are private, protected, and public. | In Interface, only one specifier is used- Public. |
How to declare an interface
It is the same as declaring a class. However, we must use the “interface” keyword instead of class.
Syntax of Java Interface
interface Interface_name { Data types; Methods (); }
How to implement Java Interface
See the following example of the Ip.java file.
// AppInterface.java interface firstInterface { void func(); } class App implements firstInterface { public void func() { System.out.println("Implementing interface firstInterface"); } } class AppInterface { public static void main(String []args) { App app = new App(); app.func(); } }
See the output.
This is how a class implements an interface. First, it has to provide the body of all the methods declared in an interface; in other words, the class must implement all the interface methods.
See the second example.
interface car { void drive(); } class Tesla implements car { public void drive() { System.out.println("Tesla implementing Car Interface"); } } class AppInterface { public static void main(String []args) { Tesla models = new Tesla(); models.drive(); } }
See the below output.
Methods in an interface are, by default, an abstract method. Therefore, whenever any class implements an interface, we must define every interface method; otherwise, the class will turn into an abstract class. In the above case, drive() is an abstract method in an interface car, and it is defined in a Tesla class.
Inheritance in Java Interface
One class extends another class in the same way one interface can extend another interface. Here also extends keyword is used to extend the interface.
See the below code example of Java Interface Inheritance.
// Extend.java interface Printable { void print(); } interface Showable extends Printable { void show(); } class Extend implements Showable { public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]) { Extend obj = new Extend(); obj.print(); obj.show(); } }
The output is following.
Multiple Inheritance by Interface
If the class implements multiple interfaces or extends them, it is known as Multiple inheritance by the interface in Java.
See the below code example.
// Multi.java //creating interfaces interface Printable { //declaring abstarct method void print(); } interface Showable { //declaring abstarct method void show(); } //Multi class implememnting multiple inheritance class Multi implements Printable,Showable { //defining methods of interface Printable public void print(){System.out.println("App");} //defining methods of interface Showable public void show(){System.out.println("Dividend");} //Driver class public static void main(String args[]) { //creating object Multi obj = new Multi(); //calling print method from printable obj.print(); //calling show method from showable obj.show(); } }
See the output below.
Why is multiple inheritance not allowed through class but possible by an interface?
Using multiple inheritance through the class creates ambiguity, but in the case of interface, there is no ambiguity.
Let’s do this with the help of an example.
// Mul.java interface X { public void myMethod(); } //creating interface interface Y { public void myMethod(); } // implementing multiple inheritance class Mul implements X, Y { //defining methods public void myMethod() { System.out.println("Implementing more than one interfaces"); } public static void main(String args[]) { //creating object Mul obj = new Mul(); obj.myMethod(); } }
See the output.
Default Method in Interface: Java 8
After Java 8, there is a Method where we can declare the method body in the interface, but we need to make the method default.
Let’s see an example of that.
// DefMet.java interface Drawable { void draw(); default void msg(){System.out.println("default method");} } class Rectangle implements Drawable { public void draw(){System.out.println("drawing rectangle");} } class DefMet { public static void main(String args[]) { Drawable d=new Rectangle(); d.draw(); d.msg(); } }
See the below output.
Static Method in Interface: Java 8
Since Java 8, we can have a static method in an interface. See the below code.
// StaMet.java interface Drawable { void draw(); // abstract method static int square(int a){return a*a;} //static method } class Rectangle implements Drawable { //delaring abstract method public void draw(){System.out.println("drawing rectangle");} } //Driver class class StaMet { public static void main(String args[]) { Drawable d=new Rectangle();//creating reference variable d.draw(); System.out.println(Drawable.square(3)); } }
See the below output.
Nested Interface in Java
If an interface is declared within another interface or a class, then the declared interface is known as the Nested interface. Nested interfaces are used to group related interface so that these are easy to maintain. However, the nested interface cannot access directly using the outer class reference or interface we can access.
If you are solving a question using a nested interface, then you need to remember two crucial points:
- The interface must be public if it is declared within another interface, but it can have any access modifier if it is declared within a class.
- Nested interfaces are declared implicitly static.
Here, we’ll discuss two types of nested interfaces—one nested class, declared within an interface, and another, declared within a class.
Example of a nested interface within an interface
See the below code.
// NestedInt1.java //outer interface creating interface Showable { void show(); //nested interface creating within a interface interface Welcome { void msg(); } } //decalring a class for accessing nested interface class NestedInt1 implements Showable.Welcome { // defining the method of nested interface public void msg(){System.out.println("Hello,See this is nested interface");} //main method public static void main(String args[]) { //upcasting Showable.Welcome welcome=new NestedInt1(); //creating reference here welcome.msg(); } }
See the output below.
As you can see in the above example, accessing the Welcome interface by its outer Showable cannot be accessed directly.
The sun microsystem has provided a nested interface Entry in a collection framework. Entry is the subinterface of Map. Map accesses them.Entry.
We can imagine it as a box inside another box. We cannot open the outer box without opening another inner box.
Example of the nested interface within a class
Now we will be going to explain about nested interface within a class.
// NestedInt2.java // creating class class Outer { // nested interface interface Welcome { void msg(); } } //accesing the nested interface creating reference class NestedInt2 implements Outer.Welcome { //defining the method of nested class public void msg(){System.out.println("Hello see, this is a nested interface");} public static void main(String args[]) { Outer.Welcome welcome=new NestedInt2();//upcasting welcome.msg(); } }
See the output.
Advantages of Interface
- The interface provides a contract for all the implementation classes, so it’s good to code in terms of interfaces because implementation classes can’t remove the methods we are using.
- Interfaces are suitable starting points to define Type and create a top-level hierarchy in our code.
- Since the Java class can implement multiple interfaces, it’s better to use interfaces as the superclass in most cases.
See the real-life example.
// RealLife.java //creating a interface interface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a); } class Bike implements Vehicle { int speed; int gear; //difining a method to change gear public void changeGear(int newGear) { gear = newGear; } // defining a method to measure current speed public void speedUp(int increment) { speed = speed + increment; } // a method using a break public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { System.out.println("speed: " + speed + " gear: " + gear); } } class Car implements Vehicle { int speed; int gear; //defining a method to change gear public void changeGear(int newGear) { gear = newGear; } // defining a method to measure current speed public void speedUp(int increment) { speed = speed + increment; } // a method using the break public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { System.out.println("speed: " + speed + " gear: " + gear); } } class RealLife { public static void main (String[] args) { // create an instance of Bike // performing operations Bike bike = new Bike(); bike.changeGear(1); bike.speedUp(6); bike.applyBrakes(2); System.out.println("Bike present state :"); bike.printStates(); // creating instance of a car. Car car = new Car(); car.changeGear(2); car.speedUp(7); car.applyBrakes(3); System.out.println("car present state :"); car.printStates(); } }
See the output below.
That’s it for this tutorial.