The Wayback Machine - https://web.archive.org/web/20250212081640/https://www.geeksforgeeks.org/interfaces-in-java/
Open In App

Java Interface

Last Updated : 03 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods.

  • The interface in Java is a mechanism to achieve abstraction.
  • By default, variables in an interface are public, static, and final.
  • It is used to achieve abstraction and multiple inheritances in Java.
  • It is also used to achieve loose coupling.
  • In other words, interfaces primarily define methods that other classes must implement.
  • An interface in Java defines a set of behaviors that a class can implement, usually representing an IS-A relationship, but not always in every scenario.

Example:

Java
//Driver Code Starts{
import java.io.*;

// Interface Declared
//Driver Code Ends }

interface testInterface {
  
    // public, static and final
    final int a = 10;

    // public and abstract
    void display();
}

// Class implementing interface
class TestClass implements testInterface {
  
    // Implementing the capabilities of
    // Interface
    public void display(){ 
      System.out.println("Geek"); 
    }
}

class Geeks

//Driver Code Starts{
{
    public static void main(String[] args)
    {
        TestClass t = new TestClass();
        t.display();
        System.out.println(t.a);
    }

}
//Driver Code Ends }

Output
Geek
10

Note: In Java, the abstract keyword applies only to classes and methods, indicating that they cannot be instantiated directly and must be implemented. When we decide on a type of entity by its behaviour and not via attribute we should define it as an interface.

Syntax

interface {
// declare constant fields
// declare methods that abstract
// by default.
}

To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface. To implement the interface, use the implements keyword.

Relationship Between Class and Interface

A class can extend another class, and similarly, an interface can extend another interface. However, only a class can implement an interface, and the reverse (an interface implementing a class) is not allowed.

Relationship between Class and Interface

Difference Between Class and Interface

Although Class and Interface seem the same there are certain differences between Classes and Interface. The major differences between a class and an interface are mentioned below:

Class

Interface

In class, you can instantiate variables and create an object.In an interface, you must initialize variables as they are final but you can’t create an object.                       
A class can contain concrete (with implementation) methodsThe interface cannot contain concrete (with implementation) methods.
The access specifiers used with classes are private, protected, and public.In Interface only one specifier is used- Public.

Implementation: To implement an interface, we use the keyword implements

Let’s consider the example of Vehicles like bicycles, cars, and bikes share common functionalities, which can be defined in an interface, allowing each class (e.g., Bicycle, Car, Bike) to implement them in its own way. This approach ensures code reusability, scalability, and consistency across different vehicle types.

Example:

Java
import java.io.*;

interface Vehicle {
    
    // Abstract methods defined
    void changeGear(int a);
    void speedUp(int a);
    void applyBrakes(int a);
}

// Class implementing vehicle interface
class Bicycle implements Vehicle{
    
    int speed;
    int gear;
    
    // Change gear
    @Override
    public void changeGear(int newGear){
        gear = newGear;
    }
    
    // Increase speed
    @Override
    public void speedUp(int increment){
        speed = speed + increment;
    }
    
    // Decrease speed
    @Override
    public void applyBrakes(int decrement){
        speed = speed - decrement;
    }
    
    public void printStates() {
        System.out.println("speed: " + speed
            + " gear: " + gear);
    }
}

// Class implementing vehicle interface
class Bike implements Vehicle {
    
    int speed;
    int gear;
    
    // Change gear
    @Override
    public void changeGear(int newGear){
        gear = newGear;
    }
    
    // Increase speed
    @Override
    public void speedUp(int increment){
        speed = speed + increment;
    }
    
    // Decrease speed
    @Override
    public void applyBrakes(int decrement){
        speed = speed - decrement;
    }
    
    public void printStates() {
        System.out.println("speed: " + speed
            + " gear: " + gear);
    }
    
}

class Main
{    
    public static void main (String[] args) 
    {
    
        // Instance of Bicycle(Object)
        Bicycle bicycle = new Bicycle();
        
          bicycle.changeGear(2);
        bicycle.speedUp(3);
        bicycle.applyBrakes(1);
        
        System.out.print("Bicycle present state : ");
        bicycle.printStates();
        
        // Instance of Bike (Object)
        Bike bike = new Bike();
        bike.changeGear(1);
        bike.speedUp(4);
        bike.applyBrakes(3);
        
        System.out.print("Bike present state : ");
        bike.printStates();
    }
}

Output
Bicycle present state : speed: 2 gear: 2
Bike present state : speed: 1 gear: 1

Multiple Inheritance in Java Using Interface

Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But we can use multiple inheritances in Java using Interface. Let us check this with an example.

Intefaces-in-Java-2-

Example:

Java
import java.io.*;

// Add interface
interface Add{
    int add(int a,int b);
}

// Sub interface
interface Sub{
      int sub(int a,int b);
}

// Calculator class implementing
// Add and Sub 
class Cal implements Add , Sub
{
      // Method to add two numbers
      public int add(int a,int b){
          return a+b;
    }
  
      // Method to sub two numbers
      public int sub(int a,int b){
        return a-b;
    }
  
}

class GFG{
    // Main Method
    public static void main (String[] args) 
    {
          // instance of Cal class
          Cal x = new Cal();
      
          System.out.println("Addition : " + x.add(2,1));
          System.out.println("Substraction : " + x.sub(2,1));
      
    }
}

Output
Addition : 3
Substraction : 1

New Features Added in Interfaces in JDK 8

There are certain features added to Interfaces in JDK 8 update mentioned below:

1. Default Methods

  • Interfaces can define methods with default implementations.
  • Useful for adding new methods to interfaces without breaking existing implementations.
Java
// interfaces can have methods from JDK 1.8 onwards
interface TestInterface
{
    final int a = 10;
    
      default void display() {
        System.out.println("hello");
    }
}

// A class that implements the interface.
class TestClass implements TestInterface
{
    // Driver Code
      public static void main (String[] args) {
        TestClass t = new TestClass();
        t.display();
    }
}

Output
hello

2. Static Methods

  • Interfaces can now include static methods.
  • These methods are called directly using the interface name and are not inherited by implementing classes.

Another feature that was added in JDK 8 is that we can now define static methods in interfaces that can be called independently without an object. These methods are not inherited.

Java
interface TestInterface
{
    final int a = 10;
    static void display()
    {
        System.out.println("hello");
    }
}

// A class that implements the interface.
class TestClass implements TestInterface
{
    // Driver Code
    public static void main (String[] args)
    {
        TestInterface.display();
    }
}

Output
hello

Extending Interfaces

One interface can inherit another by the use of keyword extends. When a class implements an interface that inherits another interface, it must provide an implementation for all methods required by the interface inheritance chain.

Java
interface A {
    void method1();
    void method2();
}

// B now includes method1
// and method2
interface B extends A {
    void method3();
}

// the class must implement
// all method of A and B.
class GFG implements B 
{
    public void method1() {
        System.out.println("Method 1");
    }
  
    public void method2() {
        System.out.println("Method 2");
    }
  
    public void method3() {
        System.out.println("Method 3");
    }
  
      public static void main(String[] args){
          
          // Instance of GFG class created
          GFG x = new GFG();
          
          // All Methods Called
          x.method1();
          x.method2();
          x.method3();
    }
}

Output
Method 1
Method 2
Method 3


In a Simple way, the interface contains multiple abstract methods, so write the implementation in implementation classes. If the implementation is unable to provide an implementation of all abstract methods, then declare the implementation class with an abstract modifier, and complete the remaining method implementation in the next created child classes. It is possible to declare multiple child classes but at final we have completed the implementation of all abstract methods.

In general, the development process is step by step:

Level 1 – interfaces: It contains the service details.
Level 2 – abstract classes: It contains partial implementation.
Level 3 – implementation classes: It contains all implementations.
Level 4 – Final Code / Main Method: It have access of all interfaces data.

Example:

Java
// implementation Level wise
import java.io.*;
import java.lang.*;
import java.util.*;

// Level 1
interface Bank {
    void deposit();
    void withdraw();
    void loan();
    void account();
}

// Level 2
abstract class Dev1 implements Bank {
    public void deposit()
    {
        System.out.println("Your deposit Amount :" + 100);
    }
}

abstract class Dev2 extends Dev1 {
    public void withdraw()
    {
        System.out.println("Your withdraw Amount :" + 50);
    }
}

// Level 3
class Dev3 extends Dev2 {
    public void loan() {}
    public void account() {}
}

// Level 4
class Main 
{
    public static void main(String[] args)
    {
        Dev3 d = new Dev3();
        d.account();
        d.loan();
        d.deposit();
        d.withdraw();
    }
}

Output
Your deposit Amount :100
Your withdraw Amount :50

Advantages of Interfaces

  • Without bothering about the implementation part, we can achieve the security of the implementation.
  • In Java, multiple inheritances are not allowed, however, you can use an interface to make use of it as you can implement more than one interface.

New Features Added in Interfaces in JDK 9

From Java 9 onwards, interfaces can contain the following also:

  1. Static methods
  2. Private methods
  3. Private Static methods

Important Points

In the article, we learn certain important points about interfaces as mentioned below:

  • We can’t create an instance (interface can’t be instantiated) of the interface but we can make the reference of it that refers to the Object of its implementing class.
  • A class can implement more than one interface.
  • An interface can extend to another interface or interface (more than one interface).
  • A class that implements the interface must implement all the methods in the interface.
  • All the methods are public and abstract. All the fields are public, static, and final.
  • It is used to achieve multiple inheritances.
  • It is used to achieve loose coupling.
  • Inside the Interface not possible to declare instance variables because by default variables are public static final.
  • Inside the Interface, constructors are not allowed.
  • Inside the interface main method is not allowed.
  • Inside the interface, static, final, and private methods declaration are not possible.

FAQs

1. What is a marker or tagged interface?

Tagged Interfaces are interfaces without any methods they serve as a marker without any capabilities.

2. How many Types of interfaces in Java?

Types of interfaces in Java are mentioned below:

  1. Functional Interface
  2. Marker interface

3.  Why multiple inheritance is not supported through class in Java?

Multiple Inheritance is not supported through class in Java so to avoid certain challenges like Ambiguity and diamond problems.

4. Why use interfaces when we have abstract classes?

The reason is, that abstract classes may contain non-final variables, whereas variables in the interface are final, public, and static.

// A simple interface
interface Player {
final int id = 10;
int move();
}



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg