Interface in Java – Uncover the Difference Between Classes and Interfaces

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

We have learned about interfaces in the article “Abstraction in Java”. In this article, we will take a deeper look at Interface in Java. Let us look at a real-life example for interfaces.

You must be knowing about simple interests from school arithmetic. You also must be knowing about the formula for calculating the simple interest for a given principal amount. But consider the case of different banks throughout the world. They calculate the simple interest by the same formula but they have their own rates of interest. Hence the same method name would be useful to the banks but their implementations would be completely different.

Now let us assume that a computer has the prototype of the function that calculates interest. This computer does not have the implementation of the function. It simply knows that there is a function that is useful for calculating interest. This computer is now an interface.

Interface in Java

Interface in Java

Interfaces in Java are similar to abstract classes but with some key differences. These are essential for defining a blueprint of the class methods. It is one of the methods programmers use to achieve abstraction. They contain names of methods that will be implemented in classes using this interface.

1. Interfaces store specifications and details about a class. They contain information about the class behavior

2. It contains all the functions that a class can perform. For example, an interface for a car would have break(), accelerate(), turn() methods.

3. A class whilst implementing an interface must implement all the methods inside the interface. However, it can choose not to implement all the methods if the class itself is abstract.

4. One of the popular interfaces in Java is the Comparator interface. which is useful for sorting containers.

Why use Java Interfaces?

Interfaces are useful for a variety of reasons in Java. They are:

  • To achieve loose coupling
  • To implement multiple inheritances in Java.
  • For achieving abstraction in your programs.

Declaring Interface in Java

The syntax for using interfaces is simple. For declaring an interface,

interface <interface_name>
{
//Method names
}

Interface Variables in Java

Interfaces can contain variables. However, it is redundant to declare variables inside interfaces because the class can contain the same variables. Whenever you declare a variable inside an interface, the variable automatically becomes public, static, and final. It is advisable not to use interface variables in Java.

Interface Methods in Java

Interface methods are essential because these methods are redefined in the classes. They do not contain method bodies. They simply contain the access specifier, the name, the return type and the parameters to the function. These are similar to abstract methods we learned about in the previous lesson on abstraction in java.

We will see an example of interface variables and methods while implementing interfaces in Java. All of the methods in an interface are public.

Implementing Interfaces in Java

When we want to implement an interface in a class, we use the following syntax.

class <class_name> implements <interface_name>

Once you implement interfaces, you should define all the methods inside the interface or declare the class implementing the interface as abstract.

Java program to illustrate the use of interfaces in Java:

package com.dataflair.interfaces;
interface ShootType {
  //This interface houses all the methods which will be implemented in the program. 
  public void shoot();
}
class Father implements ShootType {
  public void shoot() {
    //First implementation of the method shoot()
    System.out.println("I am the father and I shoot with my right hand!");
  }
}
class Son implements ShootType {
  public void shoot() {
    //second implementation of the method shoot. 
    System.out.println("I am the son. My father uses the right hand to shoot. I use my left hand to shoot!");
  }
}
public class InterfacesJava {
  public static void main(String[] args) {
    Father f = new Father();
    Son s = new Son();
    f.shoot();
    s.shoot();
  }
}

Output

I am the father and I shoot with my right hand!
I am the son. My father uses the right hand to shoot. I use my left hand to shoot!

Extending Multiple Inheritance in Java

You cannot implement multiple inheritance in Java by using the extends keyword. However, you can use interfaces to implement multiple inheritance. How? We will see an example

Java program to illustrate the implementation of multiple inheritance by using interfaces:

package com.dataflair.interfaces;
interface Accelerate {
  public void acceleratemethod();
}
interface Brake {
  public void brakemethod();
}
class Car implements Accelerate,
Brake {
  public void brakemethod() {
    System.out.println("This car has disc brakes");
  }
  public void acceleratemethod() {
    System.out.println("This car has BENZ OM654 engine with 503 HP");
  }
}
class MultipleInheritance {
  public static void main(String[] args) {
    Car carobject = new Car();
    carobject.acceleratemethod();
    carobject.brakemethod();
  }
}

Output

This car has BENZ OM654 engine with 503 HP
This car has disc brakes

We observe that the two interfaces act as abstract classes. This is similar to extending two abstract classes inside a third class. This is how we implement multiple inheritance in Java.

Tag Interface or Empty Interface in Java

These are the interfaces that do not have any methods or variables within it. They are empty interfaces. One popular example of such an interface is the Serializable interface. Well if they are empty, why are they useful? You might be thinking. These are not useful for the programmer; rather, it is useful for the JVM(Java Virtual Machine) to assign the class to a particular type.

For example, the Serializable interface is a popular interface in Java. But it is empty. Whenever a class implements this interface, the JVM understands the class is going to perform Serialization inside it.

In general Tag interfaces look like this:

interface <interface_name>
{}

Java Nested Interface

As the name suggests, nested interfaces are interfaces within interfaces. You can now group similar interfaces inside one single interface. Once grouped together, we can use the dot(.) operator to call nested interfaces,

Nested interfaces are of two types:

  1. Inside another interface
  2. Inside a class

Java program to illustrate the use of nested interfaces inside an interface:

package com.dataflair.interface;
interface OuterInterface {
  void display();
  interface InnerInterface {
    void myMethod();
  }
}

class NestedInterface implements OuterInterface.InnerInterface {
  public void myMethod() {
    System.out.println("This is the nested interface method");
  }

  public static void main(String args[]) {
    NestedInterface object = new NestedInterface();
    object.myMethod();
  }
}

Output

This is the nested interface method

Java program to illustrate the use of nested interfaces inside a class:

package com.dataflair.interface;
class InterfaceClass {
  interface InnerInterface {
    void myMethod();
  }
}

class NestedInterface implements InterfaceClass.InnerInterface {
  public void myMethod() {
    System.out.println("This is the nested interface method in the class. ");
  }

  public static void main(String args[]) {
    NestedInterface object = new NestedInterface();
    object.myMethod();
  }
}

Output

This is the nested interface method in the class.

Properties of Java Interface

  • You have to implement all the methods of the interface inside the class unless the class itself is an abstract class.
    If the class is an abstract class, then you need not define all the methods in the interface. But you have to do so when you inherit the abstract class inside the main class.
  • Interfaces can have public, static, and final variables only.
    You can extend interfaces but you cannot implement them.
  • If two interfaces have the same method and a class implements both the interfaces, then the class has to implement the common method once.
  • If two different interfaces have the same method name but different return types a class will not be able to implement them.
  • However, both interfaces can have the same variable name. The variable is then accessible by <interface_name>.<variable_name>.

With the advent of new Java versions throughout the years, a lot of new features have come into being. Let us look at some of them!

New Features of Interfaces(Default, Private and Static methods in Interfaces)

1. If you are using Java version 8 or newer, you can add default implementations to your interfaces. Default implementations of functions are useful because a concrete class may not provide a specific implementation to that method. This prevents the old code from breaking if a new method is added to the interface.

2. You can also have static methods inside an interface which you can call without an object. However, these methods are non-inheritable.

3. If you are using java 9 or newer, you can have static, private, and private static methods inside your interface.

Let us look at an example program to understand the new features of Java.

Java Interface Static Methods

Interfaces can have static methods which are useful when you need to call a method directly from an interface without implementing it. You can simply call a static method of an interface the same way you call a static method inside a class.

<Interface_name>.<method_name>

Java program to illustrate the use of interface static methods:

package com.dataflair.interfaces;
interface Vehicle {
  public void accelerate();
  public static void brake() {
    System.out.println("This is a static method for braking");
  }
}

public class InterfaceStatic implements Vehicle {
  public void accelerate() {
    System.out.println("This is a nonstatic method for implementing acceleration in cars");
  }
  public static void main(String[] args) {
    InterfaceStatic object = new InterfaceStatic();
    object.accelerate();
    Vehicle.brake();
    System.out.println("Classic example of static methods in Interfaces");
  }
}

Output

This is a nonstatic method for implementing acceleration in cars
This is a static method for braking
Classic example of static methods in Interfaces

Java program to illustrate the use of new features of interfaces:

package com.dataflair.interfaces;
interface InterfaceJava {
  void run();
  static void StaticMethod() //static method
  {
    System.out.println("This is a static method");

  }
default void sleep() //default method
  {
    System.out.println("Both humans and dogs love to sleep");
  }
}
class Dog implements InterfaceJava {
  public void run() {
    System.out.println("A dog runs with the help of four legs");
  }

}
class Human implements InterfaceJava {
  public void run() {
    System.out.println("A human runs with the help of two legs");
  }
}
class Interface {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.run();
    Human human = new Human();
    human.run();
    InterfaceJava.StaticMethod();
    human.sleep();

  }
}

Output

A dog runs with the help of four legs
A human runs with the help of two legs
This is a static method
Both humans and dogs love to sleep

Advantages of Java Interface

  • Interfaces allow us to implement multiple inheritance in Java
  • You can break up the complex design of the codebase with the help of interfaces.
  • You also can easily clear dependencies between different objects,
  • Interfaces promote loose coupling.

Disadvantages of Interface in Java

Although interfaces are extremely useful in programming, they have some disadvantages too. Some of them are:

  • They are slow and limited in functionality.
  • They bring down the execution speed of the program.
  • The use of interfaces in programming is either minimal or extremely frequent, both of which destroy the functionality of the program.

Similarity and Differences Between Classes and Interfaces in Java

There are a lot of similarities in between classes and interfaces in Java. Some of them are :

  • Both of them can contain methods and variables.
  • You can see that the bytecode of an interface appears in the .class file.
  • The directory structure of interfaces must be the same as the packages they are in.

However, there are some striking differences between interfaces and class. They are:

  • You cannot create an object of an interface.
  • Any field that is inside an interface must be static and final. You cannot declare a field of any other type in an interface.
  • A single interface can extend multiple interfaces. This is something that a class in Java cannot do.
  • Interface in Java gets implemented whereas a class gets extended in Java.

Relationship Between Class and Interface in Java

ClassInterfaces
A class contains the functions and the variables. It is an individual datatype in itself. An interface only contains the behavior of the class. 
A class can have concrete methods or abstract methods. Until the release of the latest Java version interfaces could not have concrete methods. Now they can have default methods. 
Classes can have default, public, private and protected members. Interfaces can have public, static, and final variables only.

Java Types which can Implement Interfaces

There are a few types of data types that can implement interfaces inside them. They are:

  1. Java Enums
  2. Java Dynamic Proxy
  3. Nested Classes
  4. Abstract classes
  5. Classes.

Functional Interfaces in Java

Java 8 introduced the concept of functional interfaces. A functional interface is an interface that contains a single abstract method. This makes them ideal for use with lambda expressions, which are anonymous functions that can be passed as arguments to methods. Functional interfaces and lambda expressions together provide a powerful way to write concise and expressive code.

Summary

In this article, we learned about the basics of Interface in Java, why they are useful, how to use interface variables and methods, how it’s different from classes. We also came to know about the various similarities between classes and interfaces in java. Interfaces are very popular in object-oriented development and a good idea of the concept is essential for a software developer or a programmer in Java.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

3 Responses

  1. vamsi says:

    please upload the progeram based on soft ware using interface

  2. james marandi says:

    sir i like to your concept about java deffernts topic… it is too much helpful for me

Leave a Reply

Your email address will not be published. Required fields are marked *