For enquiries call:

Phone

+1-469-442-0620

HomeBlogProgrammingWhat is Java Interface and Why it's Needed?

What is Java Interface and Why it's Needed?

Published
05th Sep, 2023
Views
view count loader
Read it in
8 Mins
In this article
    What is Java Interface and Why it's Needed?

    Interfaces are blueprints for classes that define methods without implementing them. The contract enforces certain behaviors in the classes that implement it. By separating the definition of methods from their implementation, interfaces provide a way to achieve abstraction in Java. 

    Polymorphism is achieved by allowing multiple classes to implement the same interface. Providing consistency and promoting code reuse require Java interfaces, which establish a common protocol or contract among different classes.

    What is Interface in Java?

    An interface in Java is a set of abstract methods that define a contract for classes to follow. In essence, it acts as a blueprint, specifying which methods classes must implement without revealing details of how those methods will be implemented. Multiple inheritance-like behaviors can be achieved through interfaces since classes can implement multiple interfaces. The purpose of them is to achieve abstraction and establish a common behavior across different classes. 

    Why Use Java Interface?

    Interfaces in Java serve a variety of purposes. By defining common behavior without specifying implementation details, they enable the concept of abstraction. Classes can implement interfaces to inherit common functionality, allowing code reusability and modular programming. Additionally, they facilitate loose coupling by promoting interaction based on contracts rather than concrete implementations. Polymorphism in Java is achieved through interfaces, which enable objects of different classes to be treated uniformly. 

    How to Implement an Interface?

    To implement an interface in Java, a class uses the implements keyword followed by the name of the interface. The implementing class must provide concrete implementations for all the abstract methods defined in the interface. By implementing an interface, the class becomes obligated to adhere to the contract defined by the interface. It must provide the specified methods, and it can optionally provide additional methods and fields specific to the class.

    How do you Declare an Interface in Java?

    To declare an interface in Java, you use the interface keyword followed by the interface's name. Within the interface, you define abstract methods that do not contain any implementation. Interfaces can also include constant fields (static and final variables) and default methods (methods with implementation) introduced in Java 8. Interface methods are implicitly public and abstract, so there's no need to specify these modifiers explicitly.

    Types of Interfaces in Java?

    In Java, there are primarily two types of interfaces: functional interfaces and marker interfaces.

    Functional Interface

    An interface that contains only one abstract method is referred to as a functional interface. Java 8 introduced functional programming features and lambda expressions through this feature. In order to prevent the accidental addition of additional abstract methods, the @FunctionalInterface annotation is often used to mark an interface as functional.

    Marker Interface

    An interface with no methods is referred to as a marker interface. In addition to providing additional information or behavior, it marks or tags classes that implement it. Java's Serializable interface marks classes as serializable, and the Cloneable interface indicates that objects can be cloned.

    Points to Remember while Working with Interfaces

    An interface is a set of abstract methods, static methods, default methods, and static constants.

    1. Each method is by default public and abstract.
    2. It does not contain any constructor.
    3. Each variable declared in an interface is by default public, static, and final.
    4. Similar to abstract classes we can not create objects/ instances of interfaces.
    5. Not just abstraction, the interfaces can also help in achieving multiple inheritances in Java. 
    6. We can achieve 100% abstraction using interfaces.

    Below is the syntax for the interface:

    public interface IShape{
    //methods declaration. Static or default methods.
    }
    public class Circle implements IShape{
     //write behavior of all methods of IShape interface.
    }

    Now let’s understand how to achieve abstraction using interfaces in java programming:

    The way we write abstract classes, we can have an IShape as an interface and declare the common behavior for classes like Square, Circle, Triangle, etc. These methods can be a draw(), calculateArea(), etc.

    Shape as an interface:

    public interface IShape {
    void draw();
    void calculateArea();
    }

    Circle as a concrete class implementing Shape class:

    public class Circle implements IShape{
    double radius;
    double area;
    public Circle(double radius) {
    this.radius = radius;
    this.area = area;
    }
    @Override
    public void draw() {
    System.out.println("Drawing Circle!");
    }
    @Override
    public void calculateArea () {
    area= Math.PI*radius*radius;
     }
    public double getArea() {
    return area;
    }
    }

    implementing interface in java example

    Test class for testing interface:

    public class Test {
    public static void main(String[] args) {
    Circle circle = new Circle(10);
    circle. calculateArea ();
    System.out.println("Area of circle is : " + circle.getArea());
    }
    }

    Output:

    The area of the circle is: 314.1592653589793

    If you are passionate about programming and learning something new and want to boost your career then you should go for Computer Programming course.

    How Interface is Similar to a Class in Java?

    • A Java type can be defined using either an interface or a class.
    • Interfaces can also have methods and constants, just like classes.
    • Classes and interfaces can both be used as reference types.
    • Classes and interfaces can be extended or implemented by other classes and interfaces.
    • Just like classes, interfaces can be used to achieve polymorphism in Java.

    How Interface is Different From a Class in Java?

    • Interfaces cannot be instantiated, whereas classes can be instantiated to create objects.
    • Interfaces only declare method signatures without providing any implementation, while classes can provide concrete implementations for methods.
    • Classes can have instance variables, but interfaces cannot have instance variables until Java 8, where default methods allow for static and final variables.
    • Classes can have constructors, but interfaces cannot have constructors.
    • A class can extend only one superclass, but an interface can extend multiple interfaces using the extends keyword.

    Rules to Follow While Working With Java Interface

    • All methods in an interface are implicitly public and abstract, so you don't need to explicitly specify these modifiers.
    • All variables declared in an interface are implicitly public, static, and final. They are constants and cannot be reassigned.
    • To implement an interface, a class must provide concrete implementations for all the methods defined in the interface.
    • A class can implement multiple interfaces by separating them with commas in the implements clause.
    • Interfaces can extend other interfaces using the extends keyword, and a class implementing such an interface must provide implementations for all the methods inherited from both the interface it implements and the interfaces it extends.

    You should try out looking for this Java course to enhance and build skills in the areas of Java and backend development. This will give you more opportunities and interviews.

    Example to Understand Interfaces in Java:

    // Define an interface
    interface Drawable {
     void draw();
    }
    // Implement the interface in a class
    class Circle implements Drawable {
     public void draw() {
     System.out.println("Drawing a circle");
     }
    }
    // Implement the interface in another class
    class Rectangle implements Drawable {
     public void draw() {
     System.out.println("Drawing a rectangle");
     }
    }
    // Use the interface reference to achieve polymorphism
    public class Main {
     public static void main(String[] args) {
     Drawable shape1 = new Circle();
     shape1.draw(); // Output: Drawing a circle
     Drawable shape2 = new Rectangle();
     shape2.draw(); // Output: Drawing a rectangle
     }
    }

    In the interface in java example above, the Drawable interface declares the draw() method. The Circle and Rectangle classes implement the Drawable interface, providing their own implementations for the draw() method. By creating objects of the implementing classes and using the interface reference, we can achieve polymorphism and call the draw() method without knowing the specific class implementation.

    Similarities Between Interface and Abstract Class in Java

    Both interface and abstract classes are used to define common methods that can be implemented by multiple classes.

    Neither interfaces nor abstract classes can be instantiated directly; they are meant to be extended or implemented by other classes.

    Both can contain abstract methods, which are methods without implementation.

    Both can provide a level of abstraction and define a contract that implementing classes must follow.

    Advantages of Interface in Java

    • Achieving multiple inheritances: Java does not support multiple inheritances of classes, but a class can implement multiple interfaces, allowing it to inherit behavior from multiple sources.
    • Enforcing contracts: Interfaces define a contract that implementing classes must adhere to, ensuring consistent behavior across different classes.
    • Facilitating loose coupling: Interfaces provide a way to separate the definition of behavior from its implementation, promoting loose coupling between components.
    • Promoting code reusability: By implementing interfaces, classes can reuse common behavior defined in those interfaces, reducing code duplication.

    Disadvantages of Interface in Java

    • Limitations on code implementation: Interfaces only define the method signatures, not the actual implementation. This can be a limitation when a default implementation is needed across multiple implementing classes.
    • Increased complexity: Introducing interfaces can add complexity to the codebase, especially when dealing with multiple interfaces and their implementations.
    • Difficulty in evolving interfaces: Changing an existing interface can have an impact on all its implementing classes, potentially requiring modifications to multiple parts of the codebase.

    Use of Interface in Java

    • The interface defines a contract that specifies a set of methods that a class must implement. Maintainability and consistency are improved by doing this.
    • Using interfaces, you can define common behavior that can be implemented by multiple classes in order to achieve abstraction.
    • A common interface enables polymorphism, where different objects can be treated interchangeably based on their common interfaces.
    • Interfaces and abstract classes in Java share similar characteristics, including the definition of common methods. Multiple inheritances is possible through interfaces, contracts are enforced, and loose coupling is encouraged. Code implementation is limited and complexity is increased, however. As part of Java programming, interfaces enable polymorphism, abstraction, and contract provision.

    When do We Use an Interface Instead of an Abstract Class?

    When we write an abstract class we are defining the characteristics of an object type and specify what an object is.

    When writing an interface, we define the capabilities that we promise to provide. We are talking about establishing a contract about what an object can do.

    You might want to learn a programming language other than Java and here is a course for you to take up and reskill your expertise in Python. Python Programming training.

    Conclusion

    As a result, Java interfaces define a set of methods that classes must implement. It ensures consistency between classes by serving as a contract. Interfaces are needed to achieve abstraction, allowing for loose coupling and modular design. They enable code reusability, as multiple classes can implement the same interface. Interfaces also facilitate polymorphism, where objects of different classes can be treated uniformly. By providing a mechanism for defining common behavior without specifying implementation details, Java interfaces promote flexibility, maintainability, and extensibility in software development.

    Frequently Asked Questions (FAQs)

    1What is the purpose of a marker interface in Java?

    The primary purpose of a marker interface is to indicate certain characteristics or behaviors of a class to the Java runtime environment or other parts of the codebase. The presence of a marker interface on a class allows code that interacts with the class to make decisions or take actions based on the marker interface's presence.

    2What is the difference between a marker interface and a standard interface in Java?

    The main difference between a marker interface and a standard interface in Java is that a marker interface does not declare any methods, whereas a standard interface defines a set of methods that implementing classes must implement.

    3What is the purpose of a functional interface in Java?

    The purpose of a functional interface is to enable the use of lambda expressions or method references as instances of that interface. Functional interfaces in java are the foundation of functional programming in Java, allowing the use of functional-style programming constructs.

    4What is a real-time interface in java example?

    Interface in java real time example of an interface in Java can be the "Runnable" interface. The Runnable interface defines a single method called "run()" that represents a unit of work that can be executed by a thread. 

    Profile

    Vikram Gupta

    Blog Author

    A Senior Software Engineer (Backend) working for Integral Ad Science and a CS graduate, having 5+ years of experience. 

    I like to solve complex problems and work in a challenging, fast-paced, and competitive environment.  

    I have experience in analyzing and improving the efficiency, scalability, and stability of various system resources and have worked on building large-scale infrastructure applications. While developing the software applications, I emphasize System Design, Clean Architecture, and Well-Tested Code. 

    PATENTS – 1 Application Granted, 3 Applications Filed in USPTO 

    Key Skills and Expertise: 

    • Problem-Solving - Data Structures and Algorithms 
    • Java  - Core Java, Multi-threading, Collections, Design Patterns  
    • Web Services - REST and gRPC  
    • Frameworks - Hibernate, Spring Boot, Spring Data JPA 
    • Databases - MySQL, PostgreSQL 
    • Operating Systems - Linux, Windows, and iOS 
    • Infra - Docker, Kubernetes, Kafka, AWS 
    • Testing Frameworks - Junit5 
    • VCS and Tools - GIT, GitHub, BitBucket, Jira, Confluence, Bamboo, Sonar 
    • Build Tools - Maven, Gradle 
    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon