Table of contents
1.
Introduction
2.
How To Declare Interfaces?
3.
Properties of an Interface
4.
Types of Interfaces
4.1.
1. Normal Interface (or Regular Interface)
4.2.
2. Functional Interface
4.3.
3. Marker Interface
5.
Functional Interface
5.1.
Example of a functional interface:
6.
Marker Interface
6.1.
Example of a marker interface
7.
Built-in Marker Interfaces
8.
Difference Between Class and Interface
9.
Difference Between Abstraction and Interface
10.
Advantages of Interfaces in Java
11.
Frequently Asked Questions
11.1.
Can an interface have a constructor?
11.2.
Can a class implement multiple interfaces in Java?
11.3.
What is the purpose of marker interfaces in Java?
12.
Conclusion
Last Updated: Nov 18, 2024
Easy

Types of Interface in Java

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Interfaces are like a set of rules or contracts for classes in Java. They define what all methods a class must implement, but not how a class should implement them. This helps to keep your code organized and flexible and also allows one class to use many sets of rules. Interfaces help to keep separate what a class does from how it does it, which makes your code easier to manage and adapt to changes. They also allow different classes to work together and also support a form of multiple inheritance, where a class can implement multiple interfaces.

Types of Interface in Java

In this article, we will discuss the concept of interfaces in Java, such as how to declare them, their properties, and the different types of interfaces. 

How To Declare Interfaces?

In Java, an interface is declared using the `interface` keyword, followed by the name of the interface. The interface body contains abstract methods, which are declared without an implementation. 

The syntax for declaring an interface is:

access_modifier interface InterfaceName {
    // abstract methods
    return_type methodName(parameter_list);
    
    // constants
    data_type CONSTANT_NAME = value;
}


In this syntax: 

1. `access_modifier`: This specifies the visibility of the interface. It can be `public`, `protected`, or `default` (no modifier).
 

2. `interface`: The `interface` keyword is used to declare an interface.
 

3. `InterfaceName`: This is the name of the interface, which should follow the naming conventions of Java (typically using PascalCase).
 

4. Abstract methods: Inside the interface body, you declare abstract methods without providing their implementation. These methods end with a semicolon (`;`) instead of a method body.
 

5. Constants: Interfaces can also contain constants, which are static and final by default. They are declared using the `data_type CONSTANT_NAME = value;` syntax.
 

For example : 

public interface Drawable {
    void draw();
}


In this example, the `Drawable` interface declares a single abstract method `draw()` without any parameters or return type.

To use an interface, a class must implement it using the `implements` keyword, like this:

public class Circle implements Drawable {
    @Override
    public void draw() {
        // implementation of draw() method
        System.out.println("Drawing a circle");
    }
}


The `Circle` class implements the `Drawable` interface and provides the implementation for the `draw()` method.

Properties of an Interface

1. Abstract methods: Interfaces can contain abstract methods, which are declared without an implementation. These methods must be implemented by the classes that implement the interface. Abstract methods in an interface are implicitly `public` and `abstract`, so you don't need to specify these modifiers explicitly.
 

2. Constants: Interfaces can also contain constants, which are static and final by default. These constants are implicitly `public`, `static`, and `final`, so you don't need to specify these modifiers explicitly. Constants in an interface are typically used to define common values that are shared among the implementing classes.
 

3. No constructor: Unlike classes, interfaces cannot have constructors. Since interfaces do not have any implementation details, there is no need for a constructor to initialize the interface.
 

4. No instance variables: Interfaces cannot have instance variables (non-static fields). They can only contain constants, which are static and final.
 

5. Multiple inheritance: A class can implement multiple interfaces, achieving a form of multiple inheritance. This allows a class to inherit behavior from multiple interfaces, providing flexibility and modularity in the design of the class hierarchy.
 

6. Loose coupling: Interfaces promote loose coupling between classes. By defining a contract through an interface, classes can interact with each other based on the interface methods, without being tightly coupled to the specific implementation details of the classes.
 

7. Polymorphism: Interfaces enable polymorphism in Java. A variable of an interface type can reference any object of a class that implements that interface. This allows for dynamic binding and flexibility in method invocation.

Types of Interfaces

In Java, there are three main types of interfaces:

1. Normal Interface (or Regular Interface)
 

2. Functional Interface
 

3. Marker Interface


Let's discuss each of these in detail:

1. Normal Interface (or Regular Interface)

A normal interface, also known as a regular interface, is an interface that contains one or more abstract methods. It can also include default and static methods, which were introduced in Java 8. A class implementing a normal interface must provide an implementation for all the abstract methods declared in the interface.

Example:

   public interface Drawable {
       void draw();
       default void message() {
           System.out.println("Drawing...");
       }
   }
   
   public class Circle implements Drawable {
       @Override
       public void draw() {
           System.out.println("Drawing a circle");
       }
   }


In this example, `Drawable` is a normal interface with an abstract method `draw()` and a default method `message()`. The `Circle` class implements the `Drawable` interface and provides an implementation for the `draw()` method.

2. Functional Interface

 A functional interface is an interface that contains only one abstract method. It can also have default and static methods. Functional interfaces are used extensively in Java 8 and higher, particularly with lambda expressions and method references. The `@FunctionalInterface` annotation is used to mark an interface as a functional interface, ensuring that it contains only one abstract method.

Example:

   @FunctionalInterface
   public interface Executable {
       void execute();
   }
   
   public class Task implements Executable {
       @Override
       public void execute() {
           System.out.println("Executing a task");
       }
   }


In this example, `Executable` is a functional interface with a single abstract method `execute()`. The `Task` class implements the `Executable` interface and provides an implementation for the `execute()` method.

3. Marker Interface

A marker interface, also known as a tag interface, is an interface that has no methods or constants declared in it. It serves as a marker or tag for the compiler and runtime environment to indicate a specific behavior or characteristic of a class. Marker interfaces are used to provide metadata about a class and enable certain functionality.

Example:

  public interface Serializable {
       // No methods or constants
   }
   
   public class Person implements Serializable {
       private String name;
       private int age;
       
       // Constructor, getters, and setters
   }


In this example, `Serializable` is a marker interface with no methods or constants. The `Person` class implements the `Serializable` interface, indicating that instances of the `Person` class can be serialized and deserialized.

Functional Interface

A functional interface is an interface that contains only one abstract method. It is also known as a Single Abstract Method (SAM) interface. Functional interfaces are a fundamental concept in Java 8 and higher, as they enable the use of lambda expressions and method references.

Let’s discuss some of the important points about functional interfaces:

1. Single Abstract Method (SAM): A functional interface can have only one abstract method. This method represents the single functionality that the interface is designed to provide.
 

2. `@FunctionalInterface` annotation: The `@FunctionalInterface` annotation is used to mark an interface as a functional interface. It is an optional annotation, but it helps to enforce the rule of having only one abstract method and provides better compile-time checking.
 

3. Lambda expressions: Functional interfaces are the basis for lambda expressions in Java. Lambda expressions provide a concise way to implement the single abstract method of a functional interface without the need for an explicit class implementation.
 

4. Method references: Method references allow you to refer to existing methods by their name and use them as the implementation of a functional interface. They provide a compact syntax for referencing methods.

Example of a functional interface:

@FunctionalInterface
public interface Calculator {
    int calculate(int a, int b);
}


In this example, `Calculator` is a functional interface with a single abstract method `calculate()` that takes two integers as parameters and returns an integer.

Using lambda expressions with functional interfaces:

Calculator adder = (a, b) -> a + b;
Calculator subtractor = (a, b) -> a - b;

int result1 = adder.calculate(5, 3);
int result2 = subtractor.calculate(10, 7);

System.out.println("Addition: " + result1);
System.out.println("Subtraction: " + result2);


In this example, we create two instances of the `Calculator` interface using lambda expressions. The `adder` lambda expression implements the `calculate()` method to perform addition, while the `subtractor` lambda expression implements it to perform subtraction.

Output:

Addition: 8
Subtraction: 3


Note: Java has many built-in functional interfaces in the `java.util.function` package, like `Predicate`, `Consumer`, `Function`, and `Supplier`. These interfaces are designed to represent common functional patterns and can be used with lambda expressions and method references.

Marker Interface

A marker interface, which is also known as a tag interface, is an interface that has no methods or constants declared in it. It serves as a marker or tag for the compiler and runtime environment to indicate a specific behavior or characteristic of a class. Marker interfaces are used to provide metadata about a class and enable certain functionality.

Some important points to remember about Marker interface are: 

1. No methods or constants: A marker interface does not declare any methods or constants. It is an empty interface that serves solely as a marker.
 

2. Runtime behavior: Marker interfaces are used to indicate special behavior or characteristics of a class to the Java runtime environment. The presence of a marker interface can trigger specific actions or enable certain functionalities.

 

3. Compiler checks: The compiler can perform additional checks or optimizations based on the presence of a marker interface. It can enforce certain rules or generate specific code based on the interface.
 

4. Serialization: One of the most common uses of marker interfaces is for object serialization. The `Serializable` interface is a marker interface that indicates that a class can be serialized and deserialized.
 

5. Cloning: Another example of a marker interface is the `Cloneable` interface. It indicates that a class allows its objects to be cloned using the `clone()` method.

Example of a marker interface

public interface Serializable {
    // No methods or constants
}


In this example, `Serializable` is a marker interface with no methods or constants.

Using a marker interface:

public class Person implements Serializable {
    private String name;
    private int age;
    
    // Constructor, getters, and setters
}


In this example, the `Person` class implements the `Serializable` marker interface, indicating that instances of the `Person` class can be serialized and deserialized.

When an object of the `Person` class is serialized, the Java runtime environment checks if the class implements the `Serializable` interface. If it does, the object can be converted into a byte stream and stored or transmitted. Similarly, during deserialization, the runtime environment checks for the presence of the `Serializable` interface to ensure that the object can be reconstructed from the byte stream.

Note: Marker interfaces allow you to attach additional information or behavior to a class without requiring it to implement any specific methods. They convey metadata and enable specific functionality in the Java runtime environment.

Built-in Marker Interfaces

Java has many different types of built-in marker interfaces that are commonly used. These interfaces are part of the Java standard library and serve specific purposes. Let's discuss some of the common built-in marker interfaces:

1. Serializable: The `Serializable` interface is used to mark a class as serializable, indicating that objects of that class can be converted into a byte stream and stored or transmitted over a network. It allows objects to be saved to a file or sent across a network connection and then reconstructed later. The `Serializable` interface does not declare any methods; it is simply used as a marker.

Example:

   public class User implements Serializable {
       private String username;
       private String password;
       
       // Constructor, getters, and setters
   }


2. Cloneable: The `Cloneable` interface is used to indicate that a class allows its objects to be cloned. By implementing the `Cloneable` interface, a class declares that it provides a safe and legal way to create a copy of itself. To clone an object, the `clone()` method of the `Object` class is called, and it returns a new instance of the class with the same state as the original object.

Example:

   public class Person implements Cloneable {
       private String name;
       private int age;
       
       // Constructor, getters, and setters
       
       @Override
       protected Object clone() throws CloneNotSupportedException {
           return super.clone();
       }
   }


3. Remote: The `Remote` interface is used in Java Remote Method Invocation (RMI) to mark an interface as remote. It indicates that the methods declared in the interface can be invoked from a remote Java Virtual Machine (JVM). The `Remote` interface is part of the `java.rmi` package and is used in distributed computing scenarios.

Example:

   import java.rmi.Remote;
   import java.rmi.RemoteException;
   
   public interface RemoteService extends Remote {
       String sayHello(String name) throws RemoteException;
   }


These are just a few examples of built-in marker interfaces in Java. Each marker interface serves a specific purpose and provides additional information or behavior to the classes that implement them.

Note: While marker interfaces do not declare methods, they still play a crucial role in enabling many different functionalities and integrating with Java's built-in features and frameworks.

Difference Between Class and Interface

ClassInterface
A class is a blueprint or template for creating objects. It defines the properties and behaviors of objects of that class.An interface is a contract or specification that defines a set of abstract methods and constants. It specifies the behavior that a class must implement.
A class can have instance variables, constructors, and method implementations.An interface cannot have instance variables, constructors, or method implementations (except for default and static methods introduced in Java 8).
A class can extend only one superclass (single inheritance) but can implement multiple interfaces.An interface can extend multiple interfaces, allowing for a form of multiple inheritance.
A class is declared using the class keyword.An interface is declared using the interface keyword.
A class can have access modifiers such as public, private, protected, and default (package-private).An interface and its methods are implicitly public and abstract.
A class can be instantiated using the new keyword to create objects.An interface cannot be instantiated directly. It is implemented by classes, and objects of those classes can be created.
A class can have static and non-static members (variables and methods).An interface can have only static constants (fields) and abstract methods (until Java 8, which introduced default and static methods).
A class can have concrete (non-abstract) methods with implementations.An interface typically has only abstract methods without implementations (until Java 8, which introduced default methods).
A class can have constructors to initialize objects.An interface cannot have constructors.
A class can be final, which prevents it from being subclassed.An interface cannot be final, as it is meant to be implemented by classes.

Difference Between Abstraction and Interface

AbstractionInterface
Abstraction is a concept that focuses on hiding the internal details and showing only the essential features of an object. It is a way to manage complexity by providing a simplified view of an object.An interface is a contract or specification that defines a set of abstract methods and constants. It specifies the behavior that a class must implement without providing the implementation details.
Abstraction can be achieved through abstract classes or interfaces. An abstract class can have both abstract and non-abstract methods, while an interface can have only abstract methods (until Java 8, which introduced default and static methods).An interface is a pure form of abstraction. It contains only abstract methods and constants, without any implementation details (except for default and static methods introduced in Java 8).
Abstract classes can have instance variables, constructors, and method implementations, in addition to abstract methods.Interfaces cannot have instance variables, constructors, or method implementations (except for default and static methods introduced in Java 8).
A class can extend only one abstract class (single inheritance) but can implement multiple interfaces.An interface can extend multiple interfaces, allowing for a form of multiple inheritance.
Abstract classes are declared using the abstract keyword before the class declaration.Interfaces are declared using the interface keyword.
Abstract classes can have access modifiers such as public, private, protected, and default (package-private) for their methods and variables.An interface and its methods are implicitly public and abstract.
Abstract classes can provide a partial implementation of the methods, allowing subclasses to inherit and override them.Interfaces cannot provide method implementations (except for default and static methods introduced in Java 8).
Abstract classes are used when there is a need for a base implementation that subclasses can inherit and extend.Interfaces are used to define a contract that classes must follow, focusing on the behavior rather than the implementation.
Abstract classes are suitable when there is a clear hierarchical relationship between classes and a common base implementation is required.Interfaces are suitable when multiple unrelated classes need to implement a common behavior or when a class needs to implement multiple behaviors.

Advantages of Interfaces in Java

1. Abstraction: Interfaces provide a way to achieve abstraction in Java. They allow you to define a contract or specification for a set of methods that a class must implement. By using interfaces, you can focus on what needs to be done rather than how it is done. Interfaces hide the implementation details and provide a clean and simplified view of the functionality.
 

2. Multiple Inheritance: Java does not support multiple inheritance of classes, but it allows a class to implement multiple interfaces. This provides a way to achieve a form of multiple inheritance. A class can inherit behavior from multiple interfaces, allowing it to have multiple types and conform to different contracts.
 

3. Loose Coupling: Interfaces promote loose coupling between classes. When a class depends on an interface rather than a concrete implementation, it reduces the dependency between the classes. This allows for greater flexibility and easier maintenance. Classes can be developed independently as long as they adhere to the interface contract.
 

4. Polymorphism: Interfaces enable polymorphism in Java. Polymorphism allows objects of different classes to be treated as objects of a common interface type. This means that you can write code that works with objects of any class that implements a particular interface, providing flexibility and extensibility.
 

5. Modularity and Extensibility: Interfaces promote modularity and extensibility in Java programs. By defining interfaces, you can break down complex systems into smaller, more manageable parts. Different teams or developers can work on different modules that implement the same interface, promoting parallel development and code reusability.
 

6. Testing and Mocking: Interfaces make it easier to write unit tests and create mock objects. When you have classes that depend on interfaces rather than concrete implementations, you can easily create mock objects that implement the interface for testing purposes. This allows you to test classes in isolation and verify their behavior without relying on the actual implementations.
 

7. Standardization: Interfaces provide a way to standardize behavior across different classes. By defining a common interface, you can ensure that classes adhere to a specific contract and provide consistent behavior. This is particularly useful when working with libraries, frameworks, or APIs, where a set of interfaces defines the expected behavior.
 

8. Code Reusability: Interfaces promote code reusability. When you define an interface, multiple classes can implement that interface, providing their own specific implementations. This allows you to write generic code that can work with any class that implements the interface, reducing code duplication and promoting code reuse.
 

9. Evolutionary Design: Interfaces enable evolutionary design in Java programs. As requirements change over time, you can add new methods to an interface without breaking the existing classes that implement it. This allows for the evolution of the system without requiring extensive modifications to the existing codebase.

Frequently Asked Questions

Can an interface have a constructor?

No, an interface cannot have a constructor. Interfaces define a contract or specification for classes to implement and do not contain any implementation details, including constructors.

Can a class implement multiple interfaces in Java?

Yes, a class can implement multiple interfaces in Java. This allows a class to inherit behavior from multiple interfaces, achieving a form of multiple inheritance.

What is the purpose of marker interfaces in Java?

Marker interfaces in Java serve as a tag or indicator for the compiler and runtime environment. They provide metadata about a class and enable certain functionalities, such as serialization or cloning, without requiring the class to implement any specific methods.

Conclusion

In this article, we discussed the concept of interfaces in Java, including their declaration, properties, and different types. We learned about functional interfaces, marker interfaces, and some built-in interfaces provided by Java. We also discussed the differences between classes and interfaces and between abstraction and interfaces. Interfaces play a crucial role in achieving abstraction, polymorphism, loose coupling, and code reusability in Java programming. They provide a powerful mechanism for defining contracts and promoting modularity and extensibility in Java programs.

You can also check out our other blogs on Code360.

Live masterclass