Java Lambda Expression Constructor References

Introduction

We can create references to constructors.

Here is the general form of the syntax:

classname::new 
// Demonstrate a Constructor reference. 

interface MyFunc {
  MyClass func(int n);
}

class MyClass {/* www.j ava  2s  . co m*/
  private int val;

  // This constructor takes an argument.
  MyClass(int v) {
    val = v;
  }

  // This is the default constructor.
  MyClass() {
    val = 0;
  }
  int getVal() {
    return val;
  };
}

public class Main {
  public static void main(String args[]) {
    MyFunc myClassCons = MyClass::new;

    // Create an instance of MyClass via that constructor reference.
    MyClass mc = myClassCons.func(100);

    // Use the instance of MyClass just created.
    System.out.println("val is " + mc.getVal());
  }
}



PreviousNext

Related