Chapter 7. Method Enhancements

7.1.  Add static methods to interfaces

[Note]

Static Methods

Since Java 8 in addition to adding default methods to an interface, you are also able to add static methods. The syntax is similar to regular class static methods: you just use the static modifier in the method signature and include a method body:

interface Doable {
    static void doIt() {
        System.out.println("Doing it...");
    }
}
					

[Important]

Quote from JLS 8: "An interface can declare static methods, which are invoked without reference to a particular object."

This code fails to compile:

public class Task implements Doable {
    public static void main(String[] args) {
        Doable d = new Task();
        d.doIt(); // FAILS !!!
    }
}
						

This code fails to compile too:

public class Task implements Doable {
    public static void main(String[] args) {
        Task t = new Task();
        t.doIt(); // FAILS !!!
    }
}
						

This code fails to compile also:

public class Task implements Doable {
    public static void main(String[] args) {
        Task.doIt(); // FAILS !!!
    }
}
						

Only this code compiles and runs (the implements does not play any role here):

public class Task implements Doable {
    public static void main(String[] args) {
        Doable.doIt(); // Prints "Doing it..."
    }
}
						

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz