• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Can anyone explain "Reference to an instance method of an arbitrary object of a particular type"?

 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please explain "Reference to an instance method of an arbitrary object of a particular type" in Method Reference Java 8?
Why in general method isn't allowed with Employee reference:
But it is valid when you:
I could not understand by the explanation written in java docs, it would be great if anyone could help.
Thanks in advance.
kinds-of-method-references.png
[Thumbnail for kinds-of-method-references.png]
Kinds of method references
 
Saloon Keeper
Posts: 10308
217
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Employee::getId is a reference to a method that takes an Employee and returns an int. You can't assign it to a variable of type A, because A represents a function that takes no arguments and returns nothing.

instanceOfEmployee::getId refers to the same method, but it already provides an argument for the Employee parameter, so it represents a method that takes nothing, and returns an int. You can assign it to A, because A.methodA() also takes nothing, and because methodA() returns void, getId()'s int return type is ignored.

comparingInt() takes a ToIntFunction<T>, so it represents a function that takes a T and returns an int. Employee::getId fits in this case, because it's a function that takes an Employee (T) and returns an int.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!