Java: why should static interface methods have a body?

I need to have a bunch of classes with the initialize static method instead of the static {...} block, where some initialization tasks are performed. In Java 8, you can define a static interface method, but I don’t need to have a body, I just need to know that the class implements this static method.

 interface Initializable { static void initialize(){} } class Icons implements Initializable { public static void initialize(){ //... } //... } 

What is wrong with the idea of ​​using static interface methods in this case, and why is it impossible to define a static interface method without a body?

General purpose: to initialize Collection classes on application startup by calling their respective methods. Initialization tasks are: creating a connection to the database, displaying icons and graphics, analyzing the configuration of the workstation, etc.

+5
source share
1 answer

What you want is impossible. Interfaces only prescribe which instance methods should be implemented by the class.

The static method does not need an instance of the containing class to run, and therefore, if it does not need private members, it can, in principle, be placed anywhere. Starting with Java 8, it can also be placed in an interface, but it is basically an organizational function: now you can statically static methods that β€œbelong” to the interface in the interface, and you do not need to create separate classes for them (for example, the Collections class) .

Try using the following source code:

 interface A { static void f() { } } public B implements A { } 

Now an attempt to call Bf() or new B().f() will throw a compiler error. You must call the Af() method. Class B does not inherit static methods from an interface.

+5
source

All Articles