Interface in Java

In this tutorial, we will learn about Interface in Java. Interface is like an blue print of class. An Interface contain all its variable as static, final and all its methods as abstract. You can say an Interface is a complete Abstract class. We can not instantiate interface same as abstract class we can only use an interface by inheriting it our class. Some important things to remember about interface.

  • Interface contain all the final and static variables
  • Interface contain all abstract methods
  • we use interface keyword to create new interface
  • To inherit interface in class we use implements keyword.

Example Program:

// Interface
interface Bike {
  public void speed(); // interface method without body
  public void price(); // interface method without body
}

//Pulser
public class Pulser implements Bike {
  public void speed() {
    System.out.println("Max Speed 134 km/h");
  }
  public void price() {
    System.out.println("Price Rs. 1.18 lakh onwards");
  }
  
   public static void main(String[] args) {
    Pulser obj = new Pulser();  
    obj.speed();
    obj.price();
  }
}

Output:

Max Speed 134 km/h
Price Rs. 1.18 lakh onwards

Multiple Inheritance:

It is important to note we can perform multiple inheritances in case of the interface. It means we can inherit multiple interfaces in one class. Check out the following example.

// Interface
interface Bike {
  public void speed(); // interface method without body
  public void price(); // interface method without body
}

interface ExtraFeatures{
  public void showExtraFeatures(); // interface method without body
}

//Pulser
public class Pulser implements Bike, ExtraFeatures {
  public void speed() {
    System.out.println("Max Speed 134 km/h");
  }
  public void price() {
    System.out.println("Price Rs. 1.18 lakh onwards");
  }
  public void showExtraFeatures(){
    System.out.println("Tubeless Tyre, single-channel ABS");
  }
  
   public static void main(String[] args) {
    Pulser obj = new Pulser();  
    obj.speed();
    obj.price();
    obj.showExtraFeatures();
  }
}

Output:

Max Speed 134 km/h
Price Rs. 1.18 lakh onwards
Tubeless Tyre, single-channel ABS
Spread the love