4

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.

3 Answers 3

4

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;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

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

An interface is basically a list of method signatures.

2 Comments

Second statement is not true anymore as java8 added default implementation to methods in an interface
Also you can declare fields (they become static final automatically)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.