Reputation: 6081
I need to have a bunch of classes with initialize
static method instead of static {...}
block where some initialization tasks are run. In Java 8 it is possible to define static interface method but I don't need it to have a body, I just need to know the class implements this static method.
interface Initializable {
static void initialize(){}
}
class Icons implements Initializable {
public static void initialize(){
//...
}
//...
}
What's wrong with the idea of using static interface methods in this case and why it is not possible to define interface static method without a body?
General purpose is: to initialize a Collection
of classes on application start by calling their respective methods. Initialization tasks are: establishing a database connection, rendering icons and graphics, analyzing workstation configuration etc.
Upvotes: 12
Views: 7099
Reputation: 12932
What you want is not possible. Interfaces only prescribe what instance methods need to be implemented by a class.
A static method does not need an instance of the containing class to run, and thus, if it does not need private members, it can in principle be placed anywhere. Since Java 8, it can also be placed in an interface, but this is mostly an organisational feature: now you can put static methods that 'belong to' an interface in the interface, and you do not need to create separate classes for them (such as the Collections
class).
Try the following source code:
interface A {
static void f() { }
}
public B implements A { }
Now, trying to call B.f()
or new B().f()
will issue a compiler error. You need to call the method by A.f()
. The class B
does not inherit the static methods from the interface.
Upvotes: 12