Interface in Java: Complete Exploration

In this article, we will take a detailed look at Interface in Java and understand it thoroughly. So, let’s get started.

Interface in Java

What is Interface in Java ?

Interface in Java defines a set of methods that classes must implement. It allows us to achieve multiple inheritance and create code that’s more flexible and reusable. Interfaces help ensure that classes adhere to a certain contract, making our code more organized and adaptable.

Interface in Java Example

Here’s a simple example of an interface in Java:

// Define an interface named Shape
interface Shape {
    void draw(); // An abstract method without implementation
}

// Implement the Shape interface in a class
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

// Implement the Shape interface in another class
class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

// Main class to demonstrate interface usage
public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle();
        Shape rectangle = new Rectangle();
        
        circle.draw();    // Output: Drawing a circle
        rectangle.draw(); // Output: Drawing a rectangle
    }
}

In this example, the Shape interface defines a method draw(). The Circle and Rectangle classes implement this interface and provide their own implementations of the draw() method.

Difference between Class and Interface in Java

AspectClassInterface
DefinitionBlueprint for creating objects.Contract for method implementation.
InheritanceExtends one class.Implemented by multiple classes.
Multiple InheritanceNot supported (extends one class).Supported (implements multiple interfaces).
ConstructorsCan have constructors.Cannot have constructors.
FieldsCan have instance variables (fields).Can have constants (static final fields).
Method DefinitionCan have methods with implementation.Methods are abstract by default (no implementation).
Abstract ClassesCan be abstract with some methods not implemented.Cannot extend multiple classes (single inheritance).
InstantiationObjects instantiated from classes.Objects not directly instantiated from interfaces.
Access ModifiersPublic, private, protected, default.Methods are implicitly public and abstract.
ExtendingExtends another class using ‘extends’.Implements an interface using ‘implements’.
PurposeRepresents objects with attributes and behaviors.Defines method contract for implementing classes.
Use CaseCreating objects and defining behaviors.Achieving multiple inheritance and enforcing contracts.

Rules for Creating Interface in Java

Here are the rules for creating an interface in Java:

  1. Access Modifier: An interface can be declared with the access modifiers public or default .
  2. Method Declaration: Declare methods without specifying the method body. Methods are implicitly public and abstract.
  3. Constant Fields: Declare constants (static final fields) in the interface. They are implicitly public, static, and final.
  4. Extending Interfaces: An interface can extend multiple interfaces using the extends keyword.
  5. Method Signatures: Implementing classes must provide method implementations with the exact method signatures defined in the interface.
  6. Method Access Modifier: Implementing methods should have an access modifier that is either public or protected.
  7. Overriding Object Class Methods: Interfaces cannot override the equals, hashCode, and toString methods from the Object class.
  8. Inheritance Hierarchy: Sub-interfaces inherit methods and constants from parent interfaces.
  9. Implementing Classes: Classes that implement an interface must provide concrete implementations for all interface methods.
  10. Abstract Classes: Interfaces cannot be declared as abstract since they are inherently abstract.
  11. Constructor: Interfaces cannot have constructors as they cannot be instantiated directly.
  12. Default Methods (Java 8+): Interfaces can have default methods with method bodies. Implementing classes inherit default method implementations.
  13. Static Methods (Java 8+): Interfaces can have static methods with method bodies, which can be called using the interface name.
  14. Private Methods (Java 9+): Interfaces can have private methods with method bodies, primarily to assist in code organization within the interface.
  15. Functional Interfaces (Java 8+): An interface with a single abstract method is considered a functional interface and can be used with lambda expressions.

Types of Interfaces in Java

In Java, there are three types of interfaces based on their functionality and purpose. Here are the main types of interfaces:

  1. Normal Interface: This is the most common type of interface, which declares a set of abstract methods that implementing classes need to provide implementations for. Normal interfaces do not have any special qualifiers.
  2. Marker Interface: Also known as a “tag” interface, a marker interface doesn’t declare any methods. It’s used to mark a class for a certain behavior or capability. For example, the Serializable interface is a marker interface that indicates a class can be serialized.
  3. Functional Interface: A functional interface has exactly one abstract method and is used for functional programming with lambda expressions. It’s often used in conjunction with Java’s lambda expressions or method references. The java.util.function package contains several functional interfaces like Predicate, Consumer, Function, etc.

Commonly used Built-in Interfaces in Java

Here are some commonly used built-in interfaces in Java:

  1. Comparable: This interface is used to provide a natural ordering of objects. Classes that implement this interface can be sorted using methods like Collections.sort().
  2. Runnable: This interface is used to create threads by providing a run() method that contains the code to be executed by the thread.
  3. Cloneable: This interface is used to indicate that a class can be cloned using the Object.clone() method.
  4. Serializable: This interface is used to indicate that a class can be serialized, allowing its instances to be converted into a byte stream for storage or transmission.
  5. Iterable: This interface is used to make an object iterable, enabling it to be used in enhanced for loops. It requires the implementation of the iterator() method.
  6. Collection: This interface defines the basic methods for working with collections of objects, such as adding, removing, and querying elements.
  7. List: This interface extends the Collection interface and represents an ordered collection of elements. It allows duplicate elements and maintains their insertion order.
  8. Set: This interface also extends the Collection interface but represents a collection of unique elements. It does not allow duplicate elements.
  9. Map: This interface represents a collection of key-value pairs. It does not extend the Collection interface, as it focuses on the association between keys and values.
  10. Queue: This interface represents a collection designed for holding elements prior to processing. It typically follows a first-in, first-out (FIFO) order.
  11. Deque: Short for “double-ended queue,” this interface extends the Queue interface to support operations at both ends.
  12. ListIterator: This interface extends the Iterator interface and provides additional methods for iterating over lists, allowing bidirectional traversal.
  13. Function: This functional interface represents a function that takes an argument and produces a result. It is often used with lambda expressions.
  14. Predicate: Another functional interface, it represents a predicate (a condition) that takes an argument and returns a boolean value.
  15. Consumer: This functional interface represents an operation that takes an argument and performs an action without returning any result.
  16. Supplier: This functional interface represents a supplier of results, generating or providing values without taking any input.

Conclusion: Interface in Java

We explored the concept of interface in Java in great details. Interfaces serve as contracts that define methods to be implemented by classes, enabling flexible and reusable code. By allowing multiple inheritance and enforcing method contracts, interfaces enhance code organization and adaptability.

The provided code example illustrated how interfaces work, where classes implement the interface’s methods. We also explored the key distinctions between classes and interfaces, ranging from constructors to inheritance and access modifiers.

Additionally, we learned the essential rules for creating interfaces, such as access modifiers, method declarations, constant fields, and more. Different types of interfaces, including normal, marker, and functional interfaces, were discussed, each serving distinct purposes in Java programming.

Finally, we highlighted commonly used built-in interfaces, from Comparable for sorting to functional interfaces like Predicate and Supplier. These built-in interfaces play a crucial role in Java’s versatility, offering solutions for tasks like multithreading, collection manipulation, and functional programming.

Leave a Reply

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