uday
uday

Reputation: 142

Java interface and callback method

Can anyone explain the concept behind this code? I don't know what to search for or where to start? I would like to more about this type of programming.

private static interface A {
    void apply(String name, int i, int j);
}
private final A method_A = (name, i, j) -> methodOne(name, i, j);
private final A method_B = (name, i, j) -> methodTwo(name, i, j);
public void methodOne(String name, int i, int j){
    // do something
}
public void methodTwo(String name, int i, int j){
    // do some other thing
}

Thanks

Upvotes: 1

Views: 67

Answers (2)

Sweeper
Sweeper

Reputation: 271735

Your code can actually be simplfied to this:

private static interface A {
    void apply(String name, int i, int j);
}
private final A method_A = this::methodOne;
private final A method_B = this::methodTwo;
public void methodOne(String name, int i, int j){
    // do something
}
public void methodTwo(String name, int i, int j){
    // do some other thing
}

The two variables method_A and method_B are just regular variables that are of type A. The real special thing about this is the value you assign to the variables - this::methodOne.

I assume you have some knowledge about classes and interfaces and how their instances work. If not, learn those things first.

A has only one method, so you can treat it like a type that "stores" a method. I will explain why.

Prior to Java 8, you would write something like this:

private final A method_A = new A() {
    @Override
    public void apply(String name, int i, int j) {
        EnclosingClass.this.methodOne(name, i, j);
    }
};

You create an anonymous class that only has the apply method. See? Isn't the method_A object storing nothing but an implementation of a method?

Since Java 8, you can instead write this lambda expression:

private final A method_A = this::methodOne;

As you can probably guess by now, it's all syntactic sugar. You are basically saying that method_A will store methdOne. You can then pass method_A around and you are actually passing the implementation of a method!

The new stream API takes advantage of this and lets you do things like:

someList.stream().forEach(System.out::println);

Upvotes: 1

user4668606
user4668606

Reputation:

Since Java 8, interfaces with one non-default method can be expressed as lambda-expressions. Those interfaces are also called functional interfaces.

Your code creates two instances of the interface A as such lambda-expressions, which are implemented as adapters to the methods methodOne and methodTwo.

Basically this is a more compact way of writing

...

private final A method_A = new A{
    public void apply(String name, int i, int j){
        methodOne(name, i, j);
    }
};

private final A method_B = new A{
    public void apply(String name, int i, int j){
        methodOne(name, i, j);
    }
};

...

Upvotes: 2

Related Questions