简体   繁体   中英

Java interface &

I can't understand what is it??

interface A{
    void foo();
}
interface B{
    void foo();
}

then what is the result of (A & B)

        System.out.println((A & B) () -> {
            System.out.println("1");
            System.out.println("2");
        });

Could someone help me?

A & B is an intersection type. An object of this type can act as both an A and as a B .

This particular intersection type also happens to be a "functional interface" type, which means that it only has 1 abstract method. This lets you instantiate an object of this type using a lambda-expression. A & B is a "functional interface" type because both A and B have the foo -method with the exact same type signature.

So that is what this code means. You are instantiating an object of type A & B , implementing the foo -method with the lambda-function.

(A & B) () -> {
  System.out.println("1");
  System.out.println("2");
}

The System.out.println will just print out this lambda object using it's toString -method. Note that it will not call the actual foo -method. Your code will therefore just print out something similar to this: Main$$Lambda$1/1642360923@1376c05c

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