I am just trying learn some java-8
stuff and came across this script.
public class ConstructorTest {
public static void main(String[] args) {
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Test", "User");
System.out.println(person);
}
}
interface PersonFactory<P extends Person> {
P create(String firstName, String lastName);
}
class Person {
private String firstName;
private String lastName;
Person() {}
Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; }
@Override
public String toString() {
return "FirstName -> "+firstName + " : LastName ->"+ lastName;
}
}
Which looks good. But my question is, rather going for this two lines of code
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Test", "User");
System.out.println(person);
I can better go can create my Person
object in single with new
keyword right?
Person person = new Person("Test", "User");
So what is the advantage does this java-8
adding by providing this Constructor References
?
Thanks in advance.