Interface in Java

In the last tutorial we discussed abstract class which is used for achieving partial abstraction. Unlike abstract class an interface is used for full abstraction. Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user(See: Abstraction). In this guide, we will cover what is an interface in java, why we use it and what are rules that we must follow while using interfaces in Java Programming.

What is an interface in Java?

Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body, see: Java abstract method). Also, the variables declared in an interface are public, static & final by default. We will cover this in detail, later in this guide.

What is the use of interface in Java?

As mentioned above they are used for full abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than one class, However you can implement more than one interfaces in your class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

  • It is used to achieve abstraction.

  • By interface, we can support the functionality of multiple inheritance.

  • It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the 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.

Syntax:
interface { // declare constant fields // declare methods that abstract // by default. } OR interface MyInterface { /* All the methods are public abstract by default * As you see they have no body */ public void method1(); public void method2(); }
Java 8 Interface Improvement

Since Java 8, interface can have default and static methods which is discussed later.

Internal addition by the compiler
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public and abstract.

interface in java
The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface.

The relationship between class and interface
Example of an Interface in Java

This is how a class implements an interface. It has to provide the body of all the methods that are declared in interface or in other words you can say that class has to implement all the methods of interface.

Do you know? class implements interface but an interface extends another interface.

interface MyInterface { /* compiler will treat them as: * public abstract void method1(); * public abstract void method2(); */ public void method1(); public void method2(); } class Demo implements MyInterface { /* This class must have to implement both the abstract methods * else you will get compilation error */ public void method1() { System.out.println("implementation of method1"); } public void method2() { System.out.println("implementation of method2"); } public static void main(String arg[]) { MyInterface obj = new Demo(); obj.method1(); } }


Output:
implementation of method1
Java Interface Example

In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.

interface printable{ void print(); } class A6 implements printable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ A6 obj = new A6(); obj.print(); } }


Output:
Hello
Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface.

//Interface declaration: by first user interface Drawable{ void draw(); } //Implementation: by second user class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class Circle implements Drawable{ public void draw(){System.out.println("drawing circle");} } //Using interface: by third user class TestInterface1{ public static void main(String args[]){ Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable() d.draw(); }}


Output:
drawing circle
Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank interface.

interface Bank{ float rateOfInterest(); } class SBI implements Bank{ public float rateOfInterest(){return 9.15f;} } class PNB implements Bank{ public float rateOfInterest(){return 9.7f;} } class TestInterface2{ public static void main(String[] args){ Bank b=new SBI(); System.out.println("ROI: "+b.rateOfInterest()); }}


Output:
ROI: 9.15
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.

multiple inheritance in java
interface Printable{ void print(); } interface Showable{ void show(); } class A7 implements Printable,Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ A7 obj = new A7(); obj.print(); obj.show(); } }


Output:
Hello Welcome
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example:

interface Printable{ void print(); } interface Showable{ void print(); } class TestInterface3 implements Printable, Showable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ TestInterface3 obj = new TestInterface3(); obj.print(); } }


Output:
Hello
Interface inheritance
Interface and Inheritance

As discussed above, an interface can not implement another interface. It has to extend the other interface. See the below example where we have two interfaces Inf1 and Inf2. Inf2 extends Inf1 so If class implements the Inf2 it has to provide implementation of all the methods of interfaces Inf2 as well as Inf1.

A class implements an interface, but one interface extends another interface.

interface Printable{ void print(); } interface Showable extends Printable{ void show(); } class TestInterface4 implements Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ TestInterface4 obj = new TestInterface4(); obj.print(); obj.show(); } }


Output:
Hello Welcome
interface Inf1{ public void method1(); } interface Inf2 extends Inf1 { public void method2(); } public class Demo implements Inf2{ /* Even though this class is only implementing the * interface Inf2, it has to implement all the methods * of Inf1 as well because the interface Inf2 extends Inf1 */ public void method1(){ System.out.println("method1"); } public void method2(){ System.out.println("method2"); } public static void main(String args[]){ Inf2 obj = new Demo(); obj.method2(); } }


In this program, the class Demo only implements interface Inf2, however it has to provide the implementation of all the methods of interface Inf1 as well, because interface Inf2 extends Inf1.

Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an example:

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 TestInterfaceDefault{ public static void main(String args[]){ Drawable d=new Rectangle(); d.draw(); d.msg(); }}


Output:
drawing rectangle default method
Java 8 Static Method in Interface

Since Java 8, we can have static method in interface.

interface Drawable{ void draw(); static int cube(int x){return x*x*x;} } class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class TestInterfaceStatic{ public static void main(String args[]){ Drawable d=new Rectangle(); d.draw(); System.out.println(Drawable.cube(3)); }}


Output:
drawing rectangle 27
What is marker or tagged interface?

An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

An empty interface is known as tag or marker interface. For example Serializable, EventListener, Remote(java.rmi.Remote) are tag interfaces. These interfaces do not have any field and methods in it. Read more about it here.

Nested interfaces

An interface which is declared inside another interface or class is called nested interface. They are also known as inner interface. For example Entry interface in collections framework is declared inside Map interface, that’s why we don’ use it directly, rather we use it like this: Map.Entry.

Key points: Here are the key points to remember about interfaces:

  1. We can’t instantiate an interface in java. That means we cannot create the object of an interface

  2. Interface provides full abstraction as none of its methods have body. On the other hand abstract class provides partial abstraction as it can have abstract and concrete(methods with body) methods both.

  3. implements keyword is used by classes to implement an interface.

  4. While providing implementation in class of any method of an interface, it needs to be mentioned as public.

  5. Class that implements any interface must implement all the methods of that interface, else the class should be declared abstract.

  6. Interface cannot be declared as private, protected or transient.

  7. All the interface methods are by default abstract and public.

  8. Variables declared in interface are public, static and final by default.

//How Serializable interface is written? public interface Serializable{ }

Interface variables must be initialized at the time of declaration otherwise compiler will throw an error.

interface Try { int x;//Compile-time error }
Above code will throw a compile time error as the value of the variable x is not initialized at the time of declaration.

10. Inside any implementation class, you cannot change the variables declared in interface because by default, they are public, static and final. Here we are implementing the interface “Try” which has a variable x. When we tried to set the value for variable x we got compilation error as the variable x is public static final by default and final variables can not be re-initialized.

class Sample implements Try { public static void main(String args[]) { x=20; //compile time error } }

11. An interface can extend any interface but cannot implement it. Class implements interface and interface extends interface.

12. A class can implement any number of interfaces.

13. If there are two or more same methods in two interfaces and a class implements both interfaces, implementation of the method once is enough.

interface A { public void aaa(); } interface B { public void aaa(); } class Central implements A,B { public void aaa() { //Any Code here } public static void main(String args[]) { //Statements } }


14. A class cannot implement two interfaces that have methods with same name but different return type.

interface A { public void aaa(); } interface B { public int aaa(); } class Central implements A,B { public void aaa() // error { } public int aaa() // error { } public static void main(String args[]) { } }


15. Variable names conflicts can be resolved by interface name.

interface A { int x=10; } interface B { int x=100; } class Hello implements A,B { public static void Main(String args[]) { /* reference to x is ambiguous both variables are x * so we are using interface name to resolve the * variable */ System.out.println(x); System.out.println(A.x); System.out.println(B.x); } }


Nested Interface in Java

Note: An interface can have another interface which is known as a nested interface. We will learn it in detail in the nested classes chapter.

interface printable{ void print(); interface MessagePrintable{ void msg(); } }


Advantages of interface in java:

Advantages of using interfaces are as follows:

  1. Without bothering about the implementation part, we can achieve the security of implementation

  2. In java, multiple inheritance is not allowed, however you can use interface to make use of it as you can implement more than one interface.




Instagram