Java is one of the most popular languages in the programming world today. Web applications, servers, and Android programs are all created using Java. A developer who has mastered Java is and always will be in demand in the Information Technology industry. To begin, you need to understand the Object Oriented Programming (OOP) principles thoroughly. One of the tools that implement the OOP concepts is an interface in Java.

An interface in Java implements two primary Object Oriented Programming (OOP) concepts namely Abstraction and Encapsulation. You might be familiar with the concepts already. However, to refresh your memory, we will shed some light on the topics. Abstraction is the concept of hiding unnecessary details from the user and only exposing the relevant information. On the other hand, the idea of encapsulation stresses on the purpose of protecting the details of the code and its implementation from external interference and binding it all together. To implement these two concepts, we require interfaces in java.

Before further diving into the topic of the interface, we recommend you go through the basic building blocks of Java. The basics will help you gain a clear understanding of how an interface works in tandem with other components of the language and will help you understand the topic better.

What is the Basic Definition of an Interface in Java?

Two PC

An interface is kind of like a class in that it has methods and variables. However, the methods don't have bodies. Programmers generally use them to specify the behavior of an object. Also, you can't instantiate, create an instance of, that interface. You must implement the interface with a class. Then, you can create an object with that class. Additionally, an interface doesn't have any constructors like the ones you would write for a class.

For example, a Car interface might look like this:

interface Car {

}

It would have any number of methods and variables inside of the braces.

Programmers use an interface to define behaviors that multiple classes would be using the same behaviors. For example, a car dealership application might have a car class for each type of car on the lot. The class declaration might look like:

class ToyotaMatrixCar implements Car {

}

Then, you would implement all of the variables and methods in that interface. If you don't, then you will get a compiler error when you try to build the code.


Interface an Implementation of Abstraction and Encapsulation

In OOP, abstraction is a means of hiding the implementation details from the user. You don't want the average user to know precisely how all of your code is designed and implemented. Interfaces are a means of achieving abstraction.


Implementing an Interface in Java

In this section, we will learn how to declare, define and implement an interface in Java.

Declaring an interface

Using our car example above that interface might look like:

interface Car {

void setPrice(int newPrice);

int getPrice();

void setModelNumber(int newModelNumber);

int getModelNumber();

}

That defines the methods that every car class will have.

Implementing an interface

So, our car class from above might look like:

class ToyotaMatrixCar implements Car {

private int price;

private int model;

void setPrice(int NewPrice) {

this.price = newPrice;

}

int getPrice() {

return price;

}

void setModelNumber(int newModelNumber){

this.model = newModelNumber;

}

int getModelNumber(){

return model;

}

}

There you have it. Here is one possible example of a car class that would be in our application. You can add more methods if needed, but you must have the ones from the interface.


Multiple Inheritance in Java

In Java, interfaces can be used to achieve multiple inheritances. In Java, one class cannot inherit from multiple classes, so this can be accomplished using multiple interfaces.

For a straightforward example:

interface A {

void fun();

}

interface B {

void fun();

}

class AB implements A,B {

public void fun() {

System.out.println("Implementing more than one interface");

}

This example allows you to use the same method from multiple interfaces. The reason that you can't use classes for this is that it creates too much ambiguity. The compiler wouldn't know which class methods to use when you call them. The reason that the above example works is that the interface methods are abstract, you can implement them in any way you choose as long as the method definition is correct.


Important Inbuilt Interfaces in Java

The Java language comes with a library of built-in classes and interfaces. Some of these interfaces are used to create new objects and groups of objects in Java.

The Collection interface

Java collection framework
  • List
  • Map
  • Set

Some classes implement each of these interfaces. You can use these objects to create your collections of other objects. A list contains an ordered set of elements. A set is like a list, but all of the elements have to be unique. A map is a collection of values that are found using their unique key that they are stored with. These are called key-value pairs. Using these is entirely optional, but they are easy to use because they already contain the methods needed to manipulate the collection.

You can also use an array, which doesn't have quite as many rules.

The Comparable and Comparator interface

Users can define their very own methods to sort elements of a collection using the Comparable interface. The interface consists of the method compareTo (Object) that sorts the objects based on the value passed in the parameters. The method named sort (Collection collection) implicitly calls the compareTo function. However, it is mandatory for the collection of objects to implement the Comparable interface and define the compareTo function. These are used to write any kind of object that can be compared to other objects.

The Comparator interface like the Comparable interface sorts the elements of a collection. However, the interface has two methods, compare (Object obj1, Object obj2) and equals (Object obj). The interface offers the opportunity to sort the user-defined collection by data members inside the class. The sort (List list, Comparator c) function of the Collections class is used with the Comparator interface to sort the elements of the collection. One other significant difference between Comparable and Comparator interfaces is that you need to create a different class altogether to implement the Comparator over a class.

Serializable interface

The Serializable interface in Java is a marker interface. A marker interface is one which has no variables or methods declared in it. The primary purpose of the Serializable interface is to depict that the objects of the class implementing it will be converted into a stream of bytes and transported to persistent memory storage. Unlike the objects of a typical class, the objects of the class implementing Serializable interface will persist even after the program moves out of memory.


How Will Interface Help You in Efficient Coding?

Screen monitor with data

The primary advantage of coding with interfaces is that an interface exposes only the behavior of the objects rather than the object itself. This property ensures that the developer changes only the behavior of the object and not the object itself. In addition to this, using interface helps provide higher efficiency in the development lifecycle in the following ways:

Design

Interfaces make designing a large system quick and efficient. That allows developers to understand an entire system.

Development

A change in one component of the system affects the system as a whole. In Java programming, developers focus on breaking their code into multiple modules to improve efficiency. However, a change in one module leads to multiple changes which are only visible during testing. Interfaces ensure these changes are transmitted uniformly throughout the system. In addition to this, any changes in the method signature declared inside the interface are transmitted automatically to the classes implementing it.

Integration

As discussed earlier, interfaces provide the liberty to connect unrelated classes without establishing forced relationships. That helps when connecting pieces of software that have been written by different people.

Testing

The use of interface in Java also helps and aids in the testing of the code. Using interface in the code help, developers isolate bugs in a program to a subset of methods.


You Can Begin

Now that you understand the basic idea of interfaces, you can begin using them in your code. You can write your own as well as using the interfaces that Java provides with collections and Serializable interfaces. They are great tools for object-oriented design, testing, and integration of your code. You can use the interfaces in many ways to encapsulate and abstract your object's behaviors. They are great for defining methods that will be used by multiple classes.

Recommended For You