Java Interface methods

JavaObject Oriented ProgrammingProgramming

The methods in interface are abstract by default. This means methods in an interface will have only the method signature and no contents inside. Let us see an example −

Example

 Live Demo

interface Car{
   public void carSpeed();
   public void sleep();
}
class Porsche implements Car{
   public void carSpeed(){
      System.out.println("The speed of the Porsche is too much");
   }
   public void sleep(){
      System.out.println("Sleeping for few milliseconds");
   }
}
public class Demo{
   public static void main(String[] args){
      Porsche my_car = new Porsche();
      my_car.carSpeed();
      my_car.sleep();
   }
}

Output

The speed of the Porsche is too much
Sleeping for few milliseconds

An interface named ‘Car’ is defined with two functions named ‘carSpeed’ and ‘sleep’. Npw, this interface is implemented by a class named ‘Porsche’. This class defines the ‘carSpeed’ and ‘sleep’ whereas the interface had just defined them and didn’t have a body. Now, a class named Demo contains the main function that creates an instance of the Porsche class. This instance is called on ‘carSpeed’ and ‘sleep’ functions.

raja
Published on 04-Jul-2020 09:07:34
Advertisements