Write a program to give the use of interface in java

In Java, an interface is a collection of abstract methods and constants that can be implemented by a class. It defines a contract for behavior that a class must adhere to, but does not provide any implementation details. Interfaces are used to achieve abstraction, modularity, and code reusability in object-oriented programming.


Certainly! Here's an example program that demonstrates the use of interfaces in Java:


public interface Vehicle {

  void start();

  void stop();

}


public class Car implements Vehicle {

  public void start() {

    System.out.println("The car engine is starting...");

  }


  public void stop() {

    System.out.println("The car engine is stopping...");

  }


  public static void main(String[] args) {

    Vehicle myCar = new Car();

    myCar.start();

    myCar.stop();

  }

}


In this program, we have defined an interface called Vehicle with two methods, start() and stop(). The Car class implements the Vehicle interface, which means it must provide an implementation for both the start() and stop() methods.


In the main() method of the Car class, we create an instance of Car and assign it to a variable of type Vehicle. We can do this because Car implements the Vehicle interface, which means it can be treated as a Vehicle. We then call the start() and stop() methods on the myCar object.


The use of interfaces in Java allows us to define a set of methods that a class must implement, without providing any implementation details. This provides a level of abstraction that makes it easier to write code that is reusable and easier to maintain. Additionally, interfaces allow us to create "plug-and-play" code, where we can swap out different implementations of an interface as needed, without having to change the code that uses it.

Comments