Interface in java

In the last article, we learned about the abstract class which is used to achieve abstraction in java. By using the abstract class we can achieve 1% to 100% of abstraction. To achieve full abstraction, the interface was introduced in java.
In this article, we will read What is an interface in Java, how to use interface, and when to use interface in Java, use of interface in java and some important java interface example .

Here is the table content of the article will we will cover this topic.
1. What is an interface in Java?
2. Properties of an interface?
3. How to create an interface?

4. How does the compiler work after the declaration of the interface?
5. How to implements an interface?
6. When to use an interface?
7. Use of interface with Example?

8. What is multiple inheritance?
9. Why Java doesn’t support multiple inheritances?
10. How to achieve multiple inheritances?

11. What is the diamond problem in java?
12. How to resolve the diamond problem in java 8?

Video available in Hindi

What is an interface in Java?

The interface is a way to achieve abstraction in JAVA. An interface can have methods and variables like class, but the methods of an interface are by default abstract methods. It means the interface can contain only an abstract method(Method without body). The interface is used when we want to achieve full abstraction. After java 7, we can have default methods in the interface that were introduced in java 8.

An interface is a blueprint of a class and specifies what a class must do and not how to do it.
The interface has only the abstract methods, when any class implements the interface then it must provide the body of abstract methods. If a class implements an interface and doesn’t provide a body to the abstract method, then the class must be declared abstract otherwise it will throw compile time exception.

Properties of an interface

1. An interface is declared with the interface keyword.

2. The implements keyword is used by the class to implement the interface.

3. Before Java 8, An interface can have only abstract methods. It can’t have concrete methods (non-abstract methods). Since Java 8, an interface can have default methods and static methods. Since Java 9, an interface can have private methods.

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

5. An interface may also contain variables. All the variables are by default public, static and final.

6. An interface variable must be initialized at the time of declaration otherwise compiler will throw an error.

7. You can’t create an object of the interface.

8. An interface does not contain any constructor.

9. An interface can extend by another interface. A class can’t extend the interface. A class can implement it.

10. The implementation class has the responsibility to provide a body of all abstract methods else the class should be an abstract class.

11. An interface can’t be declared as private, protected, or transient.

12. A class can implement any number of interfaces by use of the comma.

13. A class cannot implement two interfaces that have methods with the same name but different return types.

 14. By the use of inheritance, we can achieve multiple inheritances which are not possible by the use of the class.

public interface MyData 
{
        // Since java 8 we can declare default method in interface
	public default void method2() 
	{
		System.out.println("method2");
	}
        // Since java 8 we can declare default method in interface
	public static void method3() 
	{
		System.out.println("method3");
	}
       	public abstract void method4();
}

How to create an interface

An interface is declared by using the interface keyword. An Interface looks like a class except for the interface keyword. During the declaration of the interface, we must take of methods because it can have only abstract methods(Method without body). But after Java 8 we can define the default method in interface. We can define variables also in the interface.

interface interfaceName
{
	// variables (by default public, static and final)
	// methods (by default public, abstract)
}
interface StudentData
{
	int rollNo = 1;
	int marks = 79;
	void showData();
	void showDetails()
}

interface: It is a keyword that is used to declare an interface.
variable: You can declare variables in the interface. The variables are public, static and final by default.
abstract method: You can declare a method in the interface. All the methods declared in the interface are public and abstract by default.

How does the compiler work after the declaration of the interface?

Interface in java

How to implement an interface?

As you have read the interface is used to achieve abstraction like an abstract class. We can’t create an object of the interface. To provide the body of abstract methods, we can implement interfaces in other classes.

When a class implements an interface, it uses the implements keyword. By use of the implements keyword all the variables and methods are inherited in class.

Class className implements interfaceName
{
	// Body of class
}
interface Student
{
	// variable in interface
	int rollNo = 1;
	int marks = 79;
	// methods in interface
	void showData();
	void showDetails();
	
}

class Marksheet implements Student
{
	@Override
	public void showData() 
	{
		System.out.println("This is implementation of show method");
	}

	@Override
	public void showDetails() 
	{
	  System.out.println("Rollno = "+ rollNo + " and marks of student = " + marks);
	}
}

public class MainClass
{
	public static void main(String arg[])
	{
		Marksheet marksheet = new Marksheet();
		marksheet.showData();
		marksheet.showDetails();
	}
}

Output:
This is implementation of show method
Rollno = 1and marks of student = 79

When to use an interface?

In Java, an interface is a complex topic for beginners. Everyone knows we use it to achieve the abstraction. But we should need to recognize the scenario when to use interface. We have seen many simple programs in which we are using the interface.  But when we are working on a large project then we should need to understand the advantage of the interface. Now, we will learn some important points of the interface that help you to understand the when to use interface in java. I will recommend you should read When to use an abstract class first. So that you can find the difference in both and use them accordingly.  

The first use of Interface is to achieve multiple inheritances. As you already know Java doesn’t support the multiple inheritances by use of classes. But it makes possible through the interface.

As you know the interface is just a blueprint or template in which we define the set of functionalities as a rule or a contract. When any concrete class implements an interface, it means it agreed upon the contract of interface. The concrete class provides the implementation of all methods of an interface.

Use of interface with Example

Suppose we have a company of Automobile. We want to manufacture new models of cars with some specific features.  A car must contain features shown below :

1. Automatic gear system
2. Model name
3. Hight tech AC

These are the rule or contract that define by us for each car. Whenever a car is manufacturing, the rules must be considered. Suppose there are two plants that manufacturing the car both should take care of the contract otherwise the process is considered unsuccessful.

when to use interface in java

Let’s achieve this task through the use of an interface. We will create an interface that defines the set of rules or contract. This interface is forcibly implemented by each class that wants to build a car. When a class implements an interface, it must provide the implementation to the abstract methods.

interface NewCarModel 
{
  public void isAutomatic();
  public void modelName();
  public void highTechAC();
}

class FirstPlant implements NewCarModel
{
	
	Car car = new Car("BMW", true, "X5.0", 5.1f, "White", "Petrol", "260bhp", 5);
	
	public void CarFeatures()
	{
		System.out.println("Brand Name : "+ car.getCompany());
		System.out.println("Color of Car : "+ car.getColor());
		System.out.println("Power : "+ car.getPower());
		System.out.println("Fuel type : "+ car.getFuelType());
		System.out.println("No of Gears: " + car.getNumberOfGear());
	}
	
	@Override
	public void isAutomatic() 
	{
		System.out.println("Is this Car automatic : " + car.isAutomatic());
	}

	@Override
	public void modelName() 
	{
		System.out.println("Model name : " + car.getModelName());
	}

	@Override
	public void highTechAC() 
	{
		System.out.println("Model name : " + car.getHighTechAC());
	}
}

class SecondPlant implements NewCarModel
{
	Car car = new Car("AUDI", true, "A5.0", 5.2f, "Black", "Disel", "280bhp", 6);

	public void CarFeatures()
	{
		System.out.println("Brand Name : "+ car.getCompany());
		System.out.println("Color of Car : "+ car.getColor());
		System.out.println("Power : "+ car.getPower());
		System.out.println("Fuel type : "+ car.getFuelType());
		System.out.println("No of Gears" + car.getNumberOfGear());
	}
	
	@Override
	public void isAutomatic() 
	{
		System.out.println("Is this Car automatic : " + car.isAutomatic());
	}

	@Override
	public void modelName() 
	{
		System.out.println("Model name : " + car.getModelName());
	}

	@Override
	public void highTechAC() 
	{
		System.out.println("Model name : " + car.getHighTechAC());
	}

}

public class MainClass
{
  public static void main(String arg[])
  {
	  System.out.println("Car manufacture in first plants");
	  FirstPlant firstPlant = new FirstPlant();
	  firstPlant.CarFeatures();
	  firstPlant.isAutomatic();
	  firstPlant.highTechAC();
	  firstPlant.modelName();
	  
	  System.out.println("Car manufacture in Second plants");
	  SecondPlant secondPlant = new SecondPlant();
	  secondPlant.CarFeatures();
	  secondPlant.isAutomatic();
	  secondPlant.highTechAC();
	  secondPlant.modelName();
  }
}

class Car
{
	String company;
	boolean isAutomatic;
	String modelName;
	float highTechAC;
	String color;
	String fuelType;
	String Power;
	int numberOfGear;
	public String getCompany() {
		return company;
	}
	public void setCompany(String company) {
		this.company = company;
	}
	public boolean isAutomatic() {
		return isAutomatic;
	}
	public void setAutomatic(boolean isAutomatic) {
		this.isAutomatic = isAutomatic;
	}
	public String getModelName() {
		return modelName;
	}
	public void setModelName(String modelName) {
		this.modelName = modelName;
	}
	public float getHighTechAC() {
		return highTechAC;
	}
	public void setHighTechAC(float highTechAC) {
		this.highTechAC = highTechAC;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public String getFuelType() {
		return fuelType;
	}
	public void setFuelType(String fuelType) {
		this.fuelType = fuelType;
	}
	public String getPower() {
		return Power;
	}
	public void setPower(String power) {
		Power = power;
	}
	public int getNumberOfGear() {
		return numberOfGear;
	}
	public void setNumberOfGear(int numberOfGear) {
		this.numberOfGear = numberOfGear;
	}
	public Car(String company, boolean isAutomatic, String modelName, float highTechAC, String color, String fuelType,
			String power, int numberOfGear) {
		this.company = company;
		this.isAutomatic = isAutomatic;
		this.modelName = modelName;
		this.highTechAC = highTechAC;
		this.color = color;
		this.fuelType = fuelType;
		Power = power;
		this.numberOfGear = numberOfGear;
	}
}

Output: Car manufacture in first plants
Brand Name : BMW
Color of Car : White
Power : 260bhp
Fuel type : Petrol
No of Gears : 5
Is this Car automatic : true
Model name : 5.1
Model name : X5.0
Car manufacture in Second plants
Brand Name : AUDI
Color of Car : Black
Power : 280bhp
Fuel type : Diesel
No of Gears: 6
Is this Car automatic : true
Model name : 5.2
Model name : A5.0

Here we have created an interface NewCarModel that has three methods isAutomatic(),modelName() and  highTechAC(). These are the abstract method so implementation will provide by the concrete class that implements it. Here we also create two concrete classes FirstPlant and SecondPlant that overriding the abstract method and gives the details of its own implementation.

3 thoughts on “Interface in java”

  1. Hi, 14. By the use of inheritance, we can achieve multiple inheritances which is not possible by the use of the class.

    Typing mistake you have done. In the above point, you have mentioned by the use of inheritance we can achieve multiple inheritances.

    It should be By the use of “Interface”

  2. All the topics are very clear and easy to understand thanks for providing such a great page to learn from basics but there is a small typing mistake When a class implements an interface,
    it uses the ” implements ” keyword but you have mentioned interface keyword ,it should be implements keyword.Thanks

Leave a Comment