Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why should static interface methods have a body?

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.

like image 807
Oleg Mikhailov Avatar asked May 25 '16 08:05

Oleg Mikhailov


People also ask

CAN interface have static methods without body?

In short, no.

Can static method in interface have body?

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.

Do interface methods have a body?

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.

Why interface has no method body?

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.


1 Answers

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.

like image 57
Hoopje Avatar answered Nov 15 '22 16:11

Hoopje