-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructorReferenceExample.java
More file actions
59 lines (49 loc) · 1.43 KB
/
ConstructorReferenceExample.java
File metadata and controls
59 lines (49 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package method_reference_and_constructor_reference;
/*
* Example demonstrating use of constructor reference
*/
import java.util.function.BiFunction;
import java.util.function.Supplier;
class Student{
private int roll;
private String name;
Student(){
System.out.println("No args. constructor");
}
Student(int roll, String name){
this.roll = roll;
this.name = name;
System.out.println("Args. constructor");
}
@Override
public String toString() {
return "Student{" +
"roll=" + roll +
", name='" + name + '\'' +
'}';
}
}
public class ConstructorReferenceExample {
/*
* maps the`Student get();` method of Supplier<Student> to the no-arg constructor of Student.
*/
static Supplier<Student> studentSupplier = Student::new;
/*
* maps the `Student apply(Integer t, String u);` method of BiFunction<Integer,String,Student>
* to the two-arg constructor of Student.
*/
static BiFunction<Integer,String,Student> studentFunction = Student::new;
public static void main(String[] args) {
System.out.println(studentSupplier.get());
System.out.println("===========");
System.out.println(studentFunction.apply(1, "Anshuman"));
}
}
/*
* Output:
* No args. constructor
* Student{roll=0, name='null'}
* ===========
* Args. constructor
* Student{roll=1, name='Anshuman'}
*/