Why can't we define a static method in a Java interface?

Java 8Object Oriented ProgrammingProgramming

From Java 8 onwards, static methods are allowed in Java 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!!!");
   }
}

Default Method Example

Create the following Java program using any editor of your choice in, say, C:\> JAVA.

Java8Tester.java

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!");
   }
}

Verify the Result

Compile the class using javac compiler as follows −

C:\JAVA>javac Java8Tester.java

Now run the Java8Tester as follows − 

C:\JAVA>java Java8Tester

Output

It should produce the following output − 

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


raja
Published on 07-Feb-2018 10:12:36
Advertisements