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.
In short, no.
Static methods in an interface since java8Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.
Interface methods do not have a body - the body is provided by the "implement" class. On implementation of an interface, you must override all of its methods. Interface methods are by default abstract and public.
Methods do certain things and in a certain way. Interfaces in contrast only state the name and arguments of methods in sort of a contract. How an implementing class implements those methods is up to the class, thus the interface cannot provide behaviour since it doesn't have an implementation of the method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With