top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Java Interfaces

Introduction

Java, one of the most widely used programming languages, offers various features enabling developers to write robust and flexible code. One such attribute is interfaces. Java interfaces play a crucial role in achieving flexibility and extensibility in software development. This blog post will explore their concept, understand their purpose, and delve into their syntax and implementing interface in java examples. So, let's demystify Java interfaces and discover how they can enhance your programming skills.


Overview

Java Interfaces provide a way to define a contract that classes must adhere to. They are a set of methods that a class implementing the interface must exhibit. By using interfaces, you can achieve total abstraction, multiple inheritance, and loose coupling in your code. They serve as a blueprint for classes and allow you to create program instructions that are more modular, reusable, and easily maintainable.

What is an Interface in Java?

In Java, an interface is a collection of abstract methods, constants, and nested types. It defines a contract that specifies what methods a class implementing an interface must have. An interface declaration is similar to a class declaration but uses the interface keyword instead of the class keyword. 

Generally, an interface can be thought of as a repository for the method signatures that will be used to implement in the code section. The degrees of abstraction get raised.

After a brief introduction to Java's interfaces, we will now discuss their necessity and advantages over the traditional use of abstract classes.

The Use of Interfaces in Java

There are different types of Interfaces in Java that are used for various purposes. Their uses are listed below.

1. Achieving Abstraction: Interfaces allow you to achieve total abstraction, where you define a contract without specifying the implementation details. This enables you to separate the interface from the implementation, making your code more modular and maintainable.

2. Java Interfaces Can Have Multiple Inheritance: Java classes can only inherit from a single superclass, but interfaces can implement multiple interfaces. This allows you to receive behavior from multiple sources, enhancing code reusability and flexibility.

3. Achieving Loose Coupling: Interfaces facilitate loose coupling between components of your code. By depending on them rather than concrete classes, you can easily swap implementations without affecting the clients that use those interfaces.

4. Creating Contracts: Interfaces provide a way to define contracts that classes must adhere to. By using these, you can ensure that classes implementing the interface provide specific functionality, making your code more reliable and predictable.

The Difference Between Class and Interface


Class

Interface

Instantiation

Can be instantiated using the ‘new’ keyword

It cannot be instantiated


Inheritance

Supports single inheritance

Supports multiple inheritance


Abstract Methods

Can have abstract and non-abstract methods

Can only have abstract methods


Constructors

Can have constructors

Cannot have constructors


Java Interface Variables

Can have instance variables

Can have only constants (static final variables)


Method Implementation

Can provide method implementations

Can only declare method signatures (no implementation)


Access Modifiers

Can have different access modifiers

Methods are implicitly public


Type of Relationship

Represents a blueprint or implementation of behavior

Represents a contract that classes must adhere to

Object Creation

Can create objects of the class

It cannot create objects directly but can be implemented by classes to create objects


Extensibility

Can extend other classes

Can extend other interfaces


Interface Implementations

Classes can implement multiple interfaces

Interfaces can extend multiple interfaces

Total Abstraction

Total abstraction refers to the concept of hiding implementation details and only exposing the essential functionality or behavior to the user. In Java, interfaces provide a way to achieve total abstraction. Let's understand this with an example:

Let's create a class called Rectangle that implements the Shape interface:

In this example, the Rectangle class implements the Shape interface, achieving total abstraction by hiding the internal details about area and perimeter calculations, allowing users to interact through the interface.

Multiple Inheritance

Multiple inheritance refers to the ability of a class to inherit characteristics and behaviors from more than one parent class. In Java, a class can take over from only one superclass but can implement multiple interfaces, allowing for different inheritances.

See the example below:

In this example, the Bird class implements both the Flyable and Swimmable interfaces, allowing it to inherit the behavior defined in both. The Bird class provides its own implementation for the fly() and swim() methods.

By using interfaces, Java allows for achieving a form of multiple inheritance. A class can implement many interfaces, enabling it to inherit and execute desired behaviors from different sources.

Loose Coupling:

Loose coupling is a design principle that promotes a modular and flexible software architecture, where components or modules are independent of each other and interact through well-defined interfaces. Java interfaces play a crucial role in achieving this.

Consider a scenario where you have two classes: OrderProcessor and PaymentGateway. The former class needs to communicate with the latter to process payments. By using interfaces, you can achieve loose coupling between OrderProcessor and PaymentGateway.

Let's see how this can be implemented:

In this example, the PaymentGateway interface defines the contract for processing payments. The OrderProcessor class has a dependency on this through its constructor. This allows for loose coupling, as the OrderProcessor class doesn't need to know the specific implementation of the payment gateway. It can interact with any class that executes the PaymentGateway interface, providing flexibility and modularity.

The use of interfaces decouples the OrderProcessor class from the concrete implementation of the payment gateway, making the code more maintainable, extensible, and testable.

Java Interface Syntax:

Use the ‘interface’ keyword to declare an interface. It is employed to offer complete abstraction. By default, all fields in an interface are public, static, and final, and all the methods are declared with an empty body. All of the methods declared must be implemented by a class that executes the interface. Use the keyword ‘implements’ to apply an interface. The following syntax is an example of a Java interface.

Nesting Interface in Java

Interfaces may be declared as members of another abstract type or class. An interface of this type is referred to as a member interface or nested interface. When declared outside of any other class, an interface in a class can only have the public and default access specifiers. 

This class-declared interface has four possible states: default, public, protected, or private. We refer to the interface as c_name when implementing it.i_name, where i_name is the name of the interface itself and c_name is the name of the class in which it is nested. 

Advantages of Interfaces in Java

Using interfaces in Java offers several advantages:

  • Modularity and Reusability: Interfaces promote modularity by separating the interface from the implementation. This allows for better code organization and the reuse of code across different classes.

  • Code Flexibility: Interfaces enable loose coupling, allowing you to swap implementations easily. This flexibility enhances code maintainability and extensibility.

  • Multiple Inheritance: Interfaces enable a class to inherit behavior from multiple sources, overcoming the limitations of single inheritance in Java.

  • Contract Enforcement: Interfaces provide a way to enforce contracts, ensuring that classes implementing an interface adhere to a specific set of methods and behavior.

Disadvantages of Interface in Java

While interfaces provide numerous benefits, there are a few considerations to keep in mind:

  • Increased Complexity: Implementing interfaces can add complexity to the codebase, especially when dealing with multiple interfaces or complex hierarchies.

  • Limited Implementation Details: Interfaces only define the method signatures and constants, not the implementation details. This can be a limitation in scenarios where you need to provide default implementations or access class-specific features.

  • Increased Indirection: There is an extra layer of indirection while relying on interfaces, which can impact performance in certain scenarios. However, modern JVM optimizations have reduced the effect significantly.

New Features Added in Interfaces in JDK 8

1. The default methods: With the release of JDK 8, Java interfaces gained additional features that enhanced their capabilities. The most notable characteristic is the introduction of default methods, which allow interfaces to provide method implementations. Here's an example:

Output:

2. Static Methods: Static methods in interfaces can be invoked independently without an object, another capability added in JDK 8. 

Output: 

Extending Interfaces

An interface can also extend another interface, enabling the creation of hierarchical relationships. When one extends the other, it inherits the methods and constants from the parent interface. Here's an example:

Output:

When implementing an interface in Java, write it as implementation classes because the interface contains numerous abstract methods. If the implementation is unable to implement all abstract methods, designate the implementation class as abstract and finish implementing the remaining methods in the subsequent child classes that are formed. Multiple child classes may be declared, but at the very end, all abstract methods have been fully implemented.

Best Practices for Using Java Interface

When using Java interfaces, following certain best practices to ensure clean, maintainable, and effective code is important. Some are listed below.

  • Keep Interfaces Focused and Cohesive: Design interfaces to have a single responsibility and focus on a specific set of related methods. Avoid creating one with too many unrelated methods, as this can lead to bloated and confusing interfaces. Instead, break down complex interfaces into smaller, more focused ones.

  • Use Descriptive and Meaningful Names: Choose descriptive and meaningful names for your interfaces that accurately reflect their purpose and functionality. This helps in understanding their intent and behavior. Avoid generic or vague names that can lead to confusion.

  • Follow the Interface Segregation Principle (ISP): The Interface Segregation Principle states that clients should not be forced to depend on interfaces they don't use. In other words, design interfaces with the user's specific needs in mind. This promotes loose coupling and prevents clients from being burdened with unnecessary dependencies.

  • Prefer Composition over Inheritance: Favor composition and interface implementation over class inheritance when designing classes that require multiple behaviors. This allows for more flexibility, as a class can implement multiple interfaces representing a specific behavior. Composition and interface implementation provides a more modular and maintainable approach compared to heavy class inheritance.

  • Keep Interfaces Stable: Once an interface is defined and used by other classes, try to keep it stable and avoid making frequent changes to its structure. Modifications can potentially break the existing implementations and demand alterations throughout the codebase. 

Conclusion

Java interfaces enable modularity, reusability, and loose coupling by providing a contract that classes must adhere to. Understanding how to use the interfaces effectively can enhance your programming skills and help you build more robust and maintainable Java applications. So embrace their power and add great potential to your Java code.

FAQs

1. How can I implement multiple interfaces in a Java class?

Answer: To implement multiple interfaces, separate them with commas in the class declaration and provide the required method implementations for each interface.

2. How can interfaces help achieve abstraction in Java?

Answer: Interfaces define a contract that classes must adhere to, allowing for abstraction by separating the interface from the implementation details. This promotes loose coupling and modularity.

3. How can interfaces support polymorphism in Java?

Answer: Interfaces enable polymorphism by allowing objects of different classes to be treated as instances of a common interface. This allows for flexible and interchangeable usage of objects based on their shared behaviors defined by the interface.

Leave a Reply

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