Interface Program in Java

Interface Program in Java: An interface is a set of rules or blueprints that a class must follow by implementing abstract methods and constants. It helps achieve abstraction and polymorphism, and classes can implement multiple interfaces.

Syntax of Interface in Java
The syntax for declaring an interface in Java is as follows:

public interface InterfaceName 
{
    // Constant declarations
    // Method declarations
}
  • The interface keyword is used to declare the interface, followed by the name of the interface.
  • The interface can contain constant declarations (fields with final values) and method declarations (methods without a body or implementation).
  • The methods declared in the interface must be implemented by any class that implements the interface.
  • To implement an interface, the class must use the implements keyword followed by the name of the interface. For example:
    public class MyClass implements InterfaceName
    {
        // Implement interface methods here
    }

How and when should interfaces be used in Java?

  • Use interfaces to achieve abstraction and polymorphism in Java.
  • They decouple implementation details of a class from its interface.
  • Interfaces can be used to define contracts that classes must follow, promoting consistency and maintainability.
  • Multiple inheritance can be simulated using interfaces in Java.
  • Facilitate the use of third-party libraries and frameworks that rely on interfaces.
  • Use interfaces to create reusable and interchangeable components.
Problem Description

Write a Java Program to show the Implementation of Interface.

advertisement
advertisement
Problem Solution

We have to enter the length and breadth of the rectangle as an input to get Area of rectangle as output.

Program/Source Code

Here is the source code of the Java Program to show the Partial Implementation of Interface. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

/*
 *  Interface Program in Java
 */
 
import java.util.Scanner;
 
interface area
{
    public void dimensions();
    public void area();
}
public class Interface_Implementation implements area
{
    int length,breadth,area;
    public void dimensions() 
    {
        Scanner s=new Scanner(System.in);
        System.out.print("Enter length:");
        length=s.nextInt();
        System.out.print("Enter breadth:");
        breadth=s.nextInt();
    }
    public void area() 
    {
        area=length*breadth;
        System.out.print("Area:"+area);
    }
    public static void main(String[] args) 
    {
        Interface_Implementation obj=new Interface_Implementation();
        obj.dimensions();
        obj.area();
    }
}
Program Explanation

1. This Java program calculates the area of a rectangle using an interface.
2. The program imports the “Scanner” class to receive user input.
3. The program declares an interface called “area” that includes two methods: “dimensions()” and “area()“.
4. The program defines a class called “Interface_Implementation” that implements the “area” interface.
5. The “dimensions()” method prompts the user to input the length and breadth of the rectangle.
6. The “area()” method calculates the area of the rectangle and prints the result.
7. The “main” method creates an object of the “Interface_Implementation” class and calls its “dimensions()” and “area()” methods to calculate and display the area of the rectangle.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Program Output
$ javac Interface_Implementation.java
$ java Interface_Implementation
 
Enter length:6
Enter breadth:7
Area:42

Advantages of Interfaces in Java

advertisement
  • Interfaces in Java provide abstraction, multiple inheritance, polymorphism, encapsulation, and testing advantages.
  • They allow for greater flexibility, reusability, and separation of concerns, as well as defining a contract between two parts of a program.
  • They also facilitate easier creation of mock objects for testing purposes.

Multiple Interfaces in Java

In Java, multiple interfaces allow a class to inherit from more than one interface, providing a way to achieve multiple inheritance. A class can implement multiple interfaces, but it can only extend one class.

interface Shape {
    void draw();
}
 
interface Color {
    void setColor(String color);
}
 
class Rectangle implements Shape, Color {
    private String color;
 
    public void draw() {
        System.out.println("Drawing Rectangle");
    }
 
    public void setColor(String color) {
        this.color = color;
    }
 
    public String getColor() {
        return color;
    }
}
 
public class Main {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();
        rectangle.draw();
        rectangle.setColor("Red");
        System.out.println("Rectangle color: " + rectangle.getColor());
    }
}
Program Explanation

1. In this program, we have two interfaces Shape and Color, and a class Rectangle that implements both of these interfaces.
2. The Shape interface defines a method draw() that the Rectangle class implements to draw a rectangle.
3. The Color interface defines a method setColor(String color) that the Rectangle class also implements to set the color of the rectangle.
4. In the main method, we create an instance of the Rectangle class and call its draw method to draw a rectangle.
5. We also set the color of the rectangle to “Red” using the setColor method and print the color using the getColor method.
6. This demonstrates how a single class can implement multiple interfaces to inherit behavior from multiple sources.

advertisement

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.