简体   繁体   中英

Interface as an method/constructor parameter

I am trying to use an existing package to create my own app upon it. However I do not know how to call an interface parametrized method.

On the package there is a class that's constructor is

public class App{
protected App(Logic logic) {
    this(logic.configuration().welcomeScreen, logic.configuration().appName, Optional.of(logic));
}
}

And the interface is this:

public interface Logic extends X, Y {

default Configuration configuration() {
    return new AppConfiguration(1000, "Hello world", true);
}
default void initialize() {
    System.out.println("Starting the application.");
}
}

And Configuration goes like this:

public final class Configuration {
public final int tick;
public final String appName;
public final boolean welcomeScreen;

public Configuration(int tick, String appName, boolean welcomeScreen) {
    this.tick = tick;
    this.appName = appName;
    this.welcomeScreen = welcomeScreen;
}
}

How do I call the App with the configurations that aren't default (1000, "Hello world", true)?

The question is similar to this: interface as a method parameter in Java but I can't grasp on the idea of having interface as parameter.

You provide a class that implements the interface and override those methods; as simple as that. default methods are overridable and your method that takes this interface as parameter can take that new class as parameter (since it implements the interface); and thus methods from the class will be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM