References to interface static methods are allowed only at source level 1.8 or above

Explanation:

In Java, static methods in an interface were introduced in Java 8. Before Java 8, interfaces could only declare method signatures and constants (final variables). With the introduction of static methods in interfaces, developers gained the ability to define and implement static methods directly in the interface itself.

To use and reference the static methods declared in an interface, your Java source code must be compiled and executed at source level 1.8 (or above). This means that you need a Java Development Kit (JDK) version 1.8 or higher to successfully compile and run code that uses static methods from an interface.

Example:

        
public interface MathUtility {
    static int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        int sum = MathUtility.add(5, 3);
        System.out.println("Sum: " + sum);
    }
}
        
    

In this example, we have an interface called MathUtility which declares a static method add(). The add() method takes two integers as parameters and returns their sum.

In the Main class, we directly call the static add() method using the interface name (MathUtility) and the method name (add()). We pass 5 and 3 as the arguments and store the result in the sum variable. Finally, we print the sum to the console.

Make sure you are using a JDK version 1.8 or above to compile and run the above code successfully. If you try to compile and run it with an older version of JDK, you will encounter an error.

Same cateogry post

Leave a comment