Java Interface – What makes it different from a Class?

You might have used an ATM machine to withdraw or deposit the payment, or for fund transfer and account information inquiries. From the perspective of programming, an interface is between two software components.

We have directly or indirectly made the use of interfaces in our programs. But we do not know the exact meaning and the use of an Interface in Java.

Today in this article, we will explore the concept of the interface in Java. An Interface, in general, is a medium through which two systems interact with each other.

Interfaces in Java

In Java, an interface is a blueprint or template of a class. It is much similar to the Java class but the only difference is that it has abstract methods and static constants.

There can be only abstract methods in an interface, that is there is no method body inside these abstract methods. The class that implements the interface should be abstract, otherwise, we need to define all the methods of the interface in the class.

Before moving ahead in this article it is recommended for you to take a quick revision on Classes in Java with Techvidvan.

Important points about Interface in Java

  • Interfaces are one of the core concepts of Java programming which are majorly used in Java design patterns.
  • An interface provides specifications of what a class should do or not and how it should do. An interface in Java basically has a set of methods that class may or may not apply.
  • It also has capabilities to perform a function. The methods in interfaces do not contain any body.
  • These abstract methods are implemented by classes before accessing them.
  • An interface in Java is a mechanism which we mainly use to achieve abstraction and multiple inheritances in Java.
  • An interface provides a set of specifications that other classes must implement.
  • We can implement multiple Java Interfaces by a Java class. All methods of an interface are implicitly public and abstract. The word abstract means these methods have no method body, only method signature.
  • Java Interface also represents the IS-A relationship of inheritance between two classes.
  • An interface can inherit or extend multiple interfaces.
  • We can implement more than one interface in our class.
  • Since Java 8, we can have static and default methods in an interface.
  • Since Java 9, we can also include private methods in an interface.

Differences between Interface and Class in Java

Difference between class and interface in java

  • Unlike a class, you cannot instantiate or create an object of an interface.
  • All the methods in an interface should be declared as abstract.
  • An interface does not contain any constructors, but a class can.
  • An interface cannot contain instance fields. It can only contain the fields that are declared as both static and final.
  • An interface can not be extended or inherited by a class; it is implemented by a class.
  • An interface cannot implement any class or another interface.

Syntax of declaring Interfaces in Java:

To declare an interface, the interface keyword is used. Here is a syntax to declare an interface:

interface interface-name
{
  //abstract methods
}

Example:

Following is an example of an interface:

//Filename: NameOfInterface.java

                    import java.lang.*;
                    // Any number of import statements

                    interface NameOfInterface
                    {
                           // Any number of final, static fields
                           // Any number of abstract method declarations
                    }

Example:

//Filename : Animal.java

interface Animal
{
   public void eat();
   public void travel();
}

Properties of a Java Interface

An Interface has the following properties −

  • An interface is implicitly abstract. While declaring an interface, you do not need to use the keyword abstract.
  • Each method of an interface is also implicitly abstract, so we need not use the abstract keyword while declaring methods inside an interface.
  • Each method in an interface is implicitly public.
  • All variables defined in an interface are public, static, and final. In other words, interfaces can declare only constants, not instance variables.

Advantages of an Interface in Java

  • Use interfaces to achieve data abstraction.
  • We also use them to support the functionality of multiple inheritances in Java.
  • We also use them for gaining loose coupling.

Hold On! It’s the right time to take a deep dive into the concept of Inheritance in Java with some real-life examples.

Note: The Java compiler automatically adds the public and abstract keywords before the methods of an interface. It also adds public, static and final keywords before the data members. It is illustrated in the image below:

Conversion of Java Interface and Methods

Implementing Interfaces in Java

A class implementing an interface can be thought of as the class assigning a contract. This means that the class agrees to perform the specific behaviors of the interface. Unless a class is declared as abstract, it should perform all the behaviors of the interface.

In order to implement an interface, a class uses the implements keyword. The implements keyword appears in the class declaration after the extends portion of the declaration.

Code to understand Interfaces in Java:

package com.techvidvan.interfaces;
interface Polygon
{
  //declaring variables of the interface
  public static final int side = 5,length = 4,breadth = 8;
  //declaring interface methods(without a method body)
  public void getName();
  public void getNumberOfSides();
  public void getArea();
  public void getPerimeter();
}

// Rectangle class "implements" the Polygon interface
class Rectangle implements Polygon
{
  public void getName()
  {
    // The body of getName() is provided here
    System.out.println("The name of the Polygon is: Rectangle");
  }
  public void getNumberOfSides()
  {
    // The body of getNumberOfSides() is provided here
    System.out.println("There are 4 sides in a Rectangle");
  }
  public void getArea()
  {
    // The body of getArea() is provided here
    System.out.println("The Area of Rectangle is: " +length*breadth);
  }
  public void getPerimeter()
  {
    // The body of getPerimeter() is provided here
    System.out.println("The Perimeter of Rectangle is: " +2*(length + breadth));
  }
}

//Square class "implements" the Polygon interface
class Square implements Polygon
{
  public void getName()
  {
    // The body of getName() is provided here
    System.out.println("\nThe name of the Polygon is: Square");
  }
  public void getNumberOfSides()
  {
    // The body of getNumberOfSides() is provided here
    System.out.println("There are 4 sides in a Rectangle");
  }
  public void getArea()
  {
    // The body of getArea() is provided here
    System.out.println("The Area of Square is: " +side * side);
  }
  public void getPerimeter()
  {
    // The body of getPerimeter() is provided here
    System.out.println("The Perimeter of Square is: " +4*side);
  }
}

class InterfaceDemo
{
  public static void main(String[] args)
  {
    Rectangle rectangle = new Rectangle(); // Create a Rectangle object
    Square square=new Square(); // Create a Square object

    //calling methods of class Rectangle
    rectangle.getName();
    rectangle.getNumberOfSides();
    rectangle.getArea();
    rectangle.getPerimeter();

    // calling methods of class Square
    square.getName();
    square.getNumberOfSides();
    square.getArea();
    square.getPerimeter();
  }
}

Output:

The name of the Polygon is: Rectangle
There are 4 sides in a Rectangle
The Area of Rectangle is: 32
The Perimeter of Rectangle is: 24
The name of the Polygon is: Square
There are 4 sides in a Rectangle
The Area of Square is: 25
The Perimeter of Square is: 20

Extending Interfaces

As a class can extend another class, similarly an interface can extend another interface. The extends keyword is used to extend or inherit an interface. The derived interface inherits the methods of the parent interface.

The following Person interface is extended by Student and Teacher interfaces.

// Filename: Person.java
public interface Person
{
       public void setName(String name);
       public void setAge(int age);
}

// Filename: Student.java
public interface Student extends Person
{
       public void marks(int marks);
       public void getEnrollmentNumber(int roll);
       public void yearOfPassing(int year);
}

// Filename: Teacher.java
public interface Teacher extends Person
{
       public void teacherId(int id);
       public void salary(int salary);
       public void assignedClasses(int number);
       public void subject(String subject);
}

The Teacher interface has four methods, but it inherits two from the Person interface; thus, a class that implements the Teacher interface needs to implement all the six methods. Similarly, a class that implements the Student interface needs to define the three methods from Student and the two methods from Person.

Extending Multiple Interfaces

We know that a Java class can only extend one parent class, as Multiple inheritances is not possible with the classes. Interfaces are similar to Java classes but an interface can extend more than one parent interface.

The multiple parent interfaces are declared in a comma-separated list after using the keyword extends.

For example, if the Dog interface extended both Animal and Pet, it would be declared as:

public interface Dog extends Pet, Animal

Relationship Between Classes and Interface

In the above figure, we can see that a class can extend another class, a class can implement an interface, and an interface can extend another interface.

New features added in interfaces from JDK 8 version

  • Before JDK 8, we could not define the static methods in interfaces. But form JDK 8, we can define the static methods in interfaces that which we can call independently without creating an object.
  • Another feature added from JDK 8 is that we can now add default implementation for methods of an interface. Suppose we want to add new functionality to an existing interface, So we will give a default body for the newly added functions with the help of default implementation. This will not affect the old codes of the interface.

New features added in interfaces from JDK 9 version

  • From the JDK 9 version onwards we can also include private methods, static methods, or private static methods in the interfaces.

Nested Interfaces

An interface that is declared inside another interface or class is called a nested interface or an inner interface.

The Nested Interface cannot be accessed directly. We mainly use a nested interface to resolve the namespace by grouping related interfaces or related interfaces and classes together.

We use the name of the outer class or outer interface followed by a dot ( . ), followed by the interface name to call the nested interface.

Get to know more about Inner Classes in Java you didn’t know about.

For Example, The Tutorial interface is present inside the Techvidvan interface. Then, we can access the Tutorial interface by calling Techvivdan.Tutorial

Some points about Nested Interface:

  • You do not need to declare the nested interfaces as static as they are ‘static’ by default.
  • You can assign any access modifier to Nested interfaces declared inside the class But the nested interface inside interface is implicitly ‘public’.

Tagging or Marker Interfaces in Java

A Tag Interface or a Marker Interface is an empty interface. These interfaces are just a tag that does not contain any fields or methods. The Tag interfaces are implemented by a class to claim membership in a set.

For example, if a class implements the EventListener interface, it is claiming to be EventListener.It is demanding to become a member of the set of EventListener classes.

Basically, these Tag interfaces are most useful to the Java Virtual Machine. We can also create our own marker or tag interfaces to categorize our code. It improves the readability of our Java code.

Syntax of writing tag interfaces

    package java.util;
    public interface Serializable
    {
        // nothing here
    }

or,

package java.util;
public interface EventListener
{
    Nothing inside the tag interface
}

Summary

Interfaces are the blueprint of classes but are not exactly the same as that of classes. Both are different in many aspects. In general words, we can say the interfaces have abstract methods that have no implementation.

Coming to the end of this article, we covered the basic concept of interfaces in Java and learned how to implement them in Java. We also learned how to extend them and use multiple interfaces using examples and programs. This article will surely help you in your future programming.

Thank you for reading our article. Do share our article on Social Media.

Happy Learning 🙂

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.