Interface

a couple of months ago

It’s one of the most complex concepts to be understood by any beginner. Usually, they get confused as to why are we using interface, the whole program is able to sail without it, then what is the need to include it in our programming?

Interface does have a lot of importance in the coding practice, which is not easily understood in the initial phase of java programming. But you will get to know the usage, as you will proceed further with the coding experience.

However, I will try my best to give the required knowledge about the interface so that you will be able to understand the same in the very starting of your Java learning cycle.

What is Interface?

An interface is similar to class in java, with a very basic and most important difference that is, it has only abstract methods in its block. It’s a way to achieve 100% abstraction in Java, where none of the methods contain any body.

Interface can contain –

  • Static Constants
  • Abstract Methods [ which is only declared, but has no body]

When to use Interface?

We could use them at the following situations:

  • When we need to achieve 100% abstraction
  • For implementing multiple inheritance [ We will discuss in detail, with example]

Declaring an Interface

The interface keyword is used to declare an interface in Java Language. Below is the syntax for the same-

Syntax

interface InterfaceName {
	//abstract methods
	//CONSTANTS
	}


Example

//Interface calculator is declared which could be used by any class
interface calculator {
	public void add();

	public void subtract();

	public void divide();

	public void multiply();

}

Properties shown by interface:

1. All the methods are abstract by default; we don’t need to use the abstract keyword explicitly.

2. While declaring an interface, we don’t need to use an abstract keyword, it is implicitly abstract in nature

Relation between class and interface

Whenever we need to use the features of another class, then we tend to use the keyword “extends” in order to inherit the properties.
Class Extending another Class
But in the case of the Interface, we can’t use the keyword extends, we need to use the keyword implements in order to define the body of the methods being declared in the interface.
Class Implementing Interface

Let’s see some more differences between Class and Interface

FeatureClassInterface
Object InstantiateCan be doneCannot be done
ConstructorsCan contain a constructorCannot contain a constructor
Nature of methodsCan be abstract & Non Abstract methodsContains only abstract methods
DeclarationDeclared using class keywordDeclared using interface keyword

Seeing the above relation, we could clearly state that interface is an impression of class, which does not contain all the properties of the class.

Working with interface

Till now we have seen a little bit about interface, now let us try to dig deep and work on the usage and implementation of it.

We need to keep certain points in mind while we are dealing with the Interface:

  • A class can implement an interface using keyword implements.
  • When a class is implementing an interface then, it means it has agreed to provide the body for all the abstract methods in the interface.
  • If a class is not able to give definitions for all the methods, then it will have to declare itself as abstract class.
  • A class can implement multiple interface.

Below is the screen, that is showing when a class Test is trying to implement the calculator interface, we are automatically given an option to implement the unimplemented abstract methods of the interface.

As soon as we click on the “Add unimplemented methods” all the methods are added to the “Test” class as below:

Example (Interface implementation)

  • Define an interface calculator
//Interface fileName - calculator.java

//Interface calculator is declared which could be used by any class
public interface calculator {
	public void add();

	public void subtract();

	public void divide();

	public void multiply();
}


  • Create a class, and implement the interface calculator
apublic class Test implements calculator {

	//Defining all the unimplemented methods of interface calculator
	@Override
	public void add() {
		// TODO Auto-generated method stub
		System.out.println("Add functionality");
	}

	@Override
	public void subtract() {
		// TODO Auto-generated method stub
		System.out.println("subtract functionality");
	}

	@Override
	public void divide() {
		// TODO Auto-generated method stub
		System.out.println("Divide functionality");
	}

	@Override
	public void multiply() {
		// TODO Auto-generated method stub
		System.out.println("Multiply functionality");
	}

	public static void main(String[] args) {

		Test obj=new Test();
		obj.add();
	}

}


In the above example we have implemented all the methods of the interface calculator and defined their body.

Now considering a situation where we don’t define one of the interface methods, then we will have to make the class as abstract.

Below Is the example illustrating the same.

public abstract class Test implements calculator {

	// Defining all the unimplemented methods of interface calculator
	@Override
	public void add() {
		// TODO Auto-generated method stub
		System.out.println("Add functionality");
	}

	@Override
	public void subtract() {
		// TODO Auto-generated method stub
		System.out.println("subtract functionality");
	}

	@Override
	public void multiply() {
		// TODO Auto-generated method stub
		System.out.println("Multiply functionality");
	}

}

Since divide () method was not defined, so we had to change the declaration of class and make it as abstract. As divide () method was the part of interface and any class implementing should have also defined divide ().

Note – Since now the class is abstract, we can’t even instantiate. It will give an error.

An interesting feature about Interface

Just like the classes can extend another class, in a similar way an interface could extend another interface. It helps the child interface to inherit the properties of the parent interface.

“extends” keyword is used for extend interface

Example –

  • Define parent interface
//Interface fileName - calculator.java

//Interface calculator is declared which could be used by any class
public interface calculator {
	public void add();

	public void subtract();

	public void divide();

	public void multiply();
}


  • Define child interface
//Interface fileName - scientificCalculator.java

//Interface scientificCalculator is declared which could be used by any class
//It is extending the calculator interface
public interface scientificCalculator extends calculator { 
	public void log();

	public void sign();
}


The scientificCalulator has its 2 methods, but it inherits 4 methods from the calculator interface. And any class that would implement scientificCalculator will now have to implement all the 6 methods (2 methods form child interface and 4 from parent interface)

NOTE : An interface could even extend multiple interfaces at once

How can we achieve multiple inheritance in Java?

Multiple inheritance means when a class inherits properties of more than one parent class. Below is the illustration for the same:

Multiple Inheritance

Can we achieve multiple inheritance by extending 2 classes in Java?

No, the problem occurs when there exist methods with same declaration in super classes and subclass. When the method is called, the compiler cannot determine which class method to be called and even on calling which class method gets the priority.

An example to support the above statement

// First Parent class 
class Parent1 {
	void add() {
		System.out.println("add methotd Parent 1");
	}
}

// Second Parent Class
class Parent2 {
	void add() {
		System.out.println("add method of Parent2");
	}
}

// child classes
class Test extends Parent1,Parent2
{

	public static void main(String args[]) {
		Test t = new Test();
		t.add(); // The compiler gets confused, which add method should be called
	}
}


Since there is add() method in both the parent classes , so the compiler at compilaton time gives error, because its not able to decide which method should be called.

To remove this impedimenet of multiple inheritence using classes, concept of interface was develoepd, that helped in implementing the multiple inheritence in Java.

A class can implement 2 interfaces to use the concept of multiple inheritance in Java. If both of the interfaces contain the same signature methods, then it’s upon the implementing class to determine which method to be used or which method should be overridden.

Example-

interface Interface1 {

	default void info() {
		System.out.println("Method of Interface 1");
	}
}

interface Interface2 {

	default void info() {
		System.out.println("Method of Interface 2");
	}
}

class Test implements Interface1, Interface2 // Implementing multiple Inheritence
{
	// Overriding show method
	public void info() {
		// use super keyword to call the info method
		// method of Interface1 interface
		Interface1.super.info();

		// use super keyword to call the info method
		// method of Interface2 interface
		Interface2.super.info();
	}

	public static void main(String args[]) {
		Test obj = new Test();
		obj.info();
	}
}

Output-

Method of Interface 1
Method of Interface 2


The above example clearly depicts the usage of implements and interface keyword in performing the multiple inheritance in Java.

Tejasvi Nanda

About the Author

Tejasvi Nanda