Llewv
Llewv

Reputation: 133

Instance initializer in interface java

Hey I was wondering if it would be possible to give some initialization to an interface when an implementer is made. Like a blank constructor in an abstract class.

I tried something like this:

public interface State {

{
//Do something.
}

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

But it does not let you have an instance initializer. Is there any way to do this? Possibly with an inner class?

So the idea is that a piece of code is automatically called when a new instance of an implementing object is created.

Upvotes: 4

Views: 1123

Answers (3)

goncalopinto
goncalopinto

Reputation: 443

An Interface doesn't work that way, it is a list of method signatures, methods that have to be implemented in a class that implements the interface. To do that you will need a class not an Interface. There is a possible solution for something like this, from Java 8 you can create static and default methods in your interface, that allows you to create methods with a body in interfaces.

Upvotes: 0

Praveen Kumar
Praveen Kumar

Reputation: 1539

You cannot have static or instance blocks in an interface. But as of java 8 you can have 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;
  }
}

Upvotes: 4

Guillaume Barré
Guillaume Barré

Reputation: 4218

You cannot do this, an interface cannot define an initializer.

An interface is basically a list of method signatures.

Upvotes: 3

Related Questions