Instance initializer in java interface

Hey, I wonder if I can initialize the interface when making the implementer It's like a blank constructor in an abstract class

I've tried something like this:

public interface State {

{
//Do something.
}

public void render();
public void tick();
}

But it won't let you have an instance initializer Is there any way to do this? There may be an internal class?

Therefore, the idea is to automatically call a piece of code when creating a new instance of the implementation object

Solution

You cannot have static or instance blocks in an interface But starting with Java 8, you can use static and default methods

public interface MyData {

default void print(String str) {
    if (!isNull(str))
        System.out.println("MyData Print::" + str);
  }

static boolean isNull(String str) {
    System.out.println("Interface Null Check");

    return str == null ? true : "".equals(str) ? true : false;
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>