• Post Reply Bookmark Topic Watch Topic
  • New Topic

::new in Java  RSS feed

 
Nandhini Sridharan
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void main( String[] args ) {
2
Defaulable defaulable = DefaulableFactory.create( DefaultableImpl::new );
3
System.out.println( defaulable.notRequired() );
4

5
defaulable = DefaulableFactory.create( OverridableImpl::new );
6
System.out.println( defaulable.notRequired() );
7
}

I recently came across the above code in one of the article. Though I understand that ::new is used to pass the instance of the class. I would love to really read and understand about ::new. Can someone has any article links about it?
 
Nandhini Sridharan
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay this is basically as part of method reference. While DefaultableImpl::new refers to constructor reference of DefaultableImpl class.

Thanks.
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is like writing new Foo. In a λ you can write Foo::new instead.
 
Rob Spoor
Sheriff
Posts: 21048
85
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Depending on the functional interface used for DefaulableFactory.create, DefaultableImpl::new can mean one of several things:

- If create takes a Supplier or Callable, it means () -> new DefaultableImpl().
- If create takes a Function (IntFunction, LongFunction, DoubleFunction), it means t -> new DefaultableImpl(t).
- If create takes a BiFunction, it means (t, u) -> new DefaultableImpl(t, u).

There are more out-of-the-box functional interfaces, and there can be even more, but you should get the picture.
 
Rahul Mahindrakar
Ranch Hand
Posts: 1869
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

If it helps

Here is the link to this part in Java Tutorial

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
 
Steve Beckle
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've found this link to be a good one for what you're looking for. http://winterbe.com/posts/2014/03/16/java-8-tutorial/
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!