Interface in Java

Consider a scenario. You have a number of classes, and all of them have to implement some certain number of methods. They can implement these method in their own way.

In java we have a special structure called Interface, where we can have declaration of methods which we want a number of classes to implement in their own way.

The basic structure of Interface is as follows :

Public interface InterfaceA{
public return-type methodA();
public return-type methodB();
}

To declare Interface use the keyword ‘interface’. The set of methods are by default ‘public’, any method you define in Interface is ‘public’.

Look at the method declaration carefully, they do not have method body. That is the purpose of creating Interface.

We just want to declare some set of methods, and leaving the implementation to the class who want to use these method. The use of Interface is very common practice in Java.

Now that we have declared an Interface, how can a class use this Interface?

Look at the below code:

First an Interface and two class ‘implementing’ the above interface. Finally, the class with main() method:

interface ComputeInterface {
	public double computeArea();
	public double computeVolume();
}

class CubeShape  implements  ComputeInterface {

	double length;
	double height;
	double width;

	CubeShape(double length, double height, double width) {
		this.length = length;
		this.height = height;
		this.width = width;
	}

	public double computeArea() {
		double area = length * width;
		return area;
	}

	public double computeVolume() {
		double volume = length * width * height;
		return volume;

	}

}

class  CylinderShape  implements  ComputeInterface {

	double radiusOfTopAndButton;
	double height;

	CylinderShape(double radiusOfTopAndButton, double height) {
		this.radiusOfTopAndButton = radiusOfTopAndButton;
		this.height = height;
	}

	public double computeArea() {

		// I recalled from my school days memory that the area of cylinder is
		// somewhat like this.
		// Okay, that was a lie, I got it by googling it.
		double area = 2 * Math.PI * radiusOfTopAndButton * radiusOfTopAndButton
				+ 2 * Math.PI * radiusOfTopAndButton * height;
		return area;
	}

	public double computeVolume() {
		double volume = Math.PI * radiusOfTopAndButton * radiusOfTopAndButton
				* height;
		return volume;
	}

}


public class InterfaceDemo {
	public static void main(String[] args) {
		CubeShape cubeShape = new CubeShape(12, 10, 10);
		System.out.println("The Area of the Cube is : "
				+ cubeShape.computeArea() + ". And the volume of Cube is : "
				+ cubeShape.computeVolume());

		CylinderShape cylinderShape = new CylinderShape(5, 12);
		System.out.println("The surface area of the cylinder is : "
				+ cylinderShape.computeArea()
				+ ". And the volume of the cylinder is : "
				+ cylinderShape.computeVolume());
	}

}

Output :

The Area of the Cube is : 120.0. And the volume of Cube is : 1200.0
The surface area of the cylinder is : 534.0707511102648. And the volume of the cylinder is : 942.4777960769379

The interface is straight forward, with two method declaration (no method body).

Check the class ‘CubeShape’. The following class definition is new to us:

public class CubeShape implements ComputeInterface

Here we have declared that the CubeShape class will implement the ComputeInterface Interface, that is in this class we have some implementation of ‘cumputeArea’ and ‘computeVolume’ methods.

Same we have done for ‘CylinderShape’ class.

Rest of the code is quite straight-forward. Run the InterfaceDemo class , and you will get this following output:

The Area of the Cube is : 120.0. And the volume of Cube is : 1200.0
The surface area of the cylinder is : 534.0707511102648. And the volume of the cylinder is : 942.4777960769379

Can you remember, while covering the concept of Inheritance, we told that a subclass objects can be assigned to super class reference.

The same applies for Interface and the class that is implementing it. You can assign an object of a class that is implementing an Interface, to the Interface reference

//add below code as just the code block not the runnable one

Create a class like below :

 

package com.java;

public class InterfaceDemo2 {

	public static void main(String[] args) {
		// a reference of ComputeInterface Interface
		ComputeInterface computeInterface;

		CubeShape cubeShape = new CubeShape(12, 10, 10);
		
                // assigning the object of CubeShape class to the Interface reference 
                'computeInterface'
		computeInterface = cubeShape;
		
		System.out.println("The Area of the Cube is : "
				+ computeInterface.computeArea()
				+ ". And the volume of Cube is : "
				+ computeInterface.computeVolume());

		CylinderShape cylinderShape = new CylinderShape(5, 12);
		
		// assigning the object of CylinderShape class to the Interface 
reference 'computeInterface'
		computeInterface = cylinderShape;
		System.out.println("The surface area of the cylinder is : "
				+ computeInterface.computeArea()
				+ ". And the volume of the cylinder is : "
				+ computeInterface.computeVolume());

	}

}

 

This class done the same work as ‘InterfaceDemo’, just in a different way. First we have declared a reference of  ComputeInterface.

ComputeInterface computeInterface;

Then we are assigning the object of CubeShape class to this reference.

computeInterface = cubeShape;

Finally, we are calling the ‘computeArea’ and ‘computeVolume’ with the ‘computeInterface’ reference.

Same thing we are doing with the object of ‘CylinderShape’ class.

Depending upon the object the ‘computeInterface’ interface is pointing to at the time of method calling, the corresponding ‘computeArea’ and ‘computeVolume’ methods will gets called.

Run the InterfaceDemo2 class, you will get the same output as before, as expected.

Note, a class which is implementing an Interface, can have some of its own method also.

But in that case, the interface reference will have no knowledge of it. Like in the above example

If CylinderShape class have a method named ‘methodABC’, you cannot call this method with ‘computeInterface’ reference. Because this reference have no knowledge what is methodABC.

Here, we will go through some more concepts of Interface.

Suppose you have a situation, where you have to ‘implement’ more than one Interface. Is it allowed? And how to do it?

It is completely allowed to implement more than one Interface.

The class declaration will look like something below :

public class classA implements Interface1, Interface2 ,….InterfaceN{
……….
method(s) from Interface1
…………
method(s) from Interface2
…………….
…………….
method(s) from InterfaceN
}

There is no limit on the numbers of Interface a class are allowed to implement. Only thing you need to take care, that the class should implement all the method(s) from all the implemented Interface(s).

On the contrary, a class can extend only a single class. There is no features provided in java which will allow a class to extend more than one class.

Suppose for some reason, you don’t want to implement all the methods of the implemented Interface. There is only one way to do it. Make the class abstract.
Check the below example:

public interface DatabaseConnectionInterface {

	public void getDatabaseDriver();
	
	public void setDatabaseConnectionUrl(String urls);
	
}

public class DatabseConnetion implements DatabaseConnectionInterface {


	public void getDatabaseDriver() {
		// TODO Auto-generated method stub
		
	}

}

Output:

Compilation Error

Errors:

DatabseConnetion.java:13: error: DatabseConnetion is not abstract and does not override abstract method setDatabaseConnectionUrl(String) in DatabaseConnectionInterface

In the above example, there is compilation error in the DatabseConnetion class, because it has not implemented one of two methods from the Interface it is implementing. Change the class like below:

package com.java;

public abstract class DatabseConnetion implements DatabaseConnectionInterface {

	public void getDatabaseDriver() {
		// TODO Auto-generated method stub

	}

}

Now, the compilation error is gone. Because we have declared the class as abstract. We are telling the compiler that this is an abstract class, so it is within the rule that the class may not implement all the method.

When I first went through this concept, an immediate question came to my mind. What if I implement both the method, and still declare the class as abstract? Will the compiler throw an error?

Just consider the rule of abstract class, it may contain one or more abstract methods. But that is not mandatory. A class may be declared as abstract and still may not have any abstract method in it.

So, answer to the above question is: No. The compiler will not throw any error.

Extend and Implement Together :

Again, consider a scenario (I hope it is not too much of hard work)!

Suppose in your class you want to extend a class and implement one or more than one Interface. Is it allowed?

Check the below code :

package com.java;

class ShapeSuperClass {
	
	public int l = 5;
	public int b = 10;	
	public void giveIntro() {
		System.out.println(" I am a super class, I don't have any work !!");
	}
}

package com.java;


interface ComputeInterface {

	public double computeArea();

	public double computeVolume();
}
package com.java;

class RectShape extends ShapeSuperClass implements ComputeInterface {

	@Override
	public double computeArea() {
		// you code goes here
		return l*b;
	}

	@Override
	public double computeVolume() {
		// your code goes here
		return 0;
	}

}

public class InterfaceExtendsDemo {
	public static void main(String []args) {
		RectShape rs = new RectShape();
		System.out.println(rs.computeArea());

}

}

Output :

50.0

See, the RectShape class is both extending a class and implementing an Interface.

Interface variables

You can have variables in Interface. The variables are implicitly public and final. You must initialize all the variables in the Interface. A class which is implementing the Interface cannot change the values of that variables.

Consider the code below :

//add this as just code block not runnable one

package com.java;

public interface InterfaceWithVariables {

	int testValue1 = 10;

	int testValue2 = 20;

	int testValue3 = 30;

}

package com.java;

package com.java;

public class IterfaceVariablesTest implements InterfaceWithVariables {

	int a = 10;

	public void doTask() {
		if (a == testValue1) {
			// do task 1
		} else if (a == testValue2) {
			// do task 2
		} else if (a == testValue3) {
			testValue2 = 50;
		}
	}

}

In the Interface, we have three variables (implicitly public and final). For curiosity purpose, you can try to make one variable anything other than ‘public’. You will get compilation error.

Now, in the class we are using these variables in a mock task management code. In the third condition block: else if (a == testValue3), you will get compilation error.

Because, we are trying to change the value of testValue2, which is a final variable, and final variable value cannot be changed.

Extend In Interface

You have seen that a class extend another class. Same goes for Interface. An Interface can extends another Interface. Check the code below :

//add this as just code block not runnable one

package com.java;

public interface InterfaceA {

	public void methodA1();
	
	public void methodA2();
}

package com.java;

public interface InterfaceB {

	public void methodB1();
	
	public void methodB2();
}

package com.java;

public interface InterfaceC extends InterfaceA, InterfaceB {

	public void methodC1();

	public void methodC2();
}

And finally a class

package com.java;

public class InterestingClass implements InterfaceC {

	public void methodA1() {
		// Your code goes here

	}

	public void methodA2() {
		// Your code goes here

	}

	public void methodB1() {
		// Your code goes here

	}

	public void methodB2() {
		// Your code goes here

	}

	public void methodC1() {
		// Your code goes here

	}

	public void methodC2() {
		// Your code goes here

	}

}

The InterfaceA and InterfaceB are nothing special.

Check the Inteface InterfaceC. It is extending both InterfaceA and InterfaceB. The rule for Interface is little less strict, it can extend more than one Interface, unlike class; a class can only extends a single class.

Finally comes our InterestingClass class. It is implementing only InterfaceC Interface. But since InterfaceC extends InterfaceA and InterfaceB.

So by chain system, it falls under the duty of InterestingClass class to implement all the methods of InterfaceA, InterfaceB and InterfaceC, in total six methods.

Below is the pictorial representation of it.


Next > < Prev
Scroll to Top