Home > Net >  How is this static method being passed in lieu of a class that implements an interface?
How is this static method being passed in lieu of a class that implements an interface?

Time:04-11

I'm not sure what's going on here. Here's an interface:

public interface AppInit {
  void create(Environment var1);
}

Here's some class's method:

  public static StandaloneModule create(AppInit appInit) {
    return new StandaloneModule(appInit);
  }

And here's how that method is being called:

StandaloneModule.create(Main::configure)

But that parameter method's signature is:

static void configure(final Environment environment) {
  ...

Why does this compile?

CodePudding user response:

Your interface is a functional interface (i.e., one abstract method). In particular it is a Consumer of type Environment. A consumer takes an argument and returns nothing. So it just consumes the argument, usually applying some type to it. Here is a more common example.

interface Consumer {
      void apply(String arg);
}

public class ConsumerDemo  {
    public static void main(String [] args) {
        SomeMethod(System.out::println);
        
    }
    
    public static void SomeMethod(Consumer con) {
        con.apply("Hello, World!");
    }
}

prints

Hello, World!

The interface need not be explicitly implemented. The compiler takes care of that by finding the appropriate interface and creating what would normally be an anonymous class.

The above was called with a method reference. It could also be called as a lambda.

a -> System.out.println(a)

Here con.apply("Hello, World!") would pass the string to to a and it would be printed.

CodePudding user response:

public interface AppInit {
  void create(Environment var1);
}

This is a Functional interface , any method that accept an AppInit as paramter can accept also a Lambda expression or a method reference .

In the case of method reference StandaloneModule.create(Main::configure) the implementation of the method void create(Environment var1); from the interface AppInit will be the method static void configure(final Environment environment).

// accept environment and return void
StandaloneModule.create(environment ->{});

// in your example it accept an Environment and return void 
// by applying the method configure on this environment like that

StandaloneModule.create(Main::configure);
// can be replaced by this code 
StandaloneModule.create(environment -> Main.configure(environment);
  • Related