1

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?

7
  • It's Object, essentially. There's no other common supertype between A and B. Commented Jul 13, 2021 at 8:54
  • Perhaps you are looking for an explanation of IntersectionType? Commented Jul 13, 2021 at 8:56
  • 1
    See also stackoverflow.com/questions/60148411/… Commented Jul 13, 2021 at 8:58
  • 3
    @FedericoklezCulloca It's not a syntax error. The type A & B is an intersection type that also happens to be a functional "interface" because A and B's foo-method has the same signature. The System.out.println will just print the toString of the lambda-object that is created. Commented Jul 13, 2021 at 9:00
  • 1
    @marstran didn't know that. Thanks for clarifying. Commented Jul 13, 2021 at 9:05

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.