Java – Why Use :: for Method References Instead of .?

javamethods

I often wonder why Java uses :: for method references instead of ., e.g. why write

  System.out::println

instead of

  System.out.println

Of course, one might simply answer: "because the designers decided so". On the other hand, I would have expected the second syntax because the dot is the usual Java syntax for accessing class members.

So is there any known special reason for introducing the new :: syntax instead of using the existing . convention for method references?

Best Answer

This is to avoid ambiguity in case if class has (static) member with the same name as method (Java allows that).

It is easy to see from code snippet in Java tutorial about method references:

Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression:

Arrays.sort(rosterAsArray, Person::compareByAge);

If class Person in above snippet would also have member named compareByAge (of the type appropriate to pass to Arrays.sort), dot notation wouldn't allow to tell whether parameter refers to method or member.