Java 8 static methods in interfaces


An interface can also have static helper methods from Java 8 onwards.

public interface vehicle {
   default void print() {
      System.out.println("I am a vehicle!");
   }
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}

Example

Live Demo

public class Java8Tester {
   public static void main(String args[]) {
      Vehicle vehicle = new Car(); vehicle.print();
   }
}
interface Vehicle {
   default void print() {
      System.out.println("I am a vehicle!");
   }
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}
interface FourWheeler {
   default void print() {
      System.out.println("I am a four wheeler!");
   }
}
class Car implements Vehicle, FourWheeler {
   public void print() {
      Vehicle.super.print();
      FourWheeler.super.print();
      Vehicle.blowHorn();
      System.out.println("I am a car!");
   }
}

Output

I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!

Updated on: 06-Feb-2020

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements