class Person
{
String name;
String add;
Person(){}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", add='" + add + '\'' +
'}';
}
public Person(String name, String add)
{
this.name=name;
this.add=add;
}
}
class PersonBuilder<E extends PersonBuilder<E>>{
String name;
String add;
E addName(String name)
{
this.name=name;
return (E)this;
}
E addAdd(String add)
{
this.add=add;
return (E)this;
}
Person build()
{
return new Person(name,add) ;
}
}
class Employee extends Person{
String doj;
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", add='" + add + '\'' +
", doj='" + doj + '\'' +
'}';
}
Employee(String name, String add, String doj)
{
super(name,add);
this.doj=doj;
}
}
class EmployeeBuilder extends PersonBuilder<EmployeeBuilder>{
String doj;
EmployeeBuilder addDoj(String doj)
{
this.doj=doj;
return this;
}
Employee build()
{
return new Employee(name,add,doj);
}
}
public class FluentBuilderRecursiveGenerics{
public static void main(String[] args) {
1. EmployeeBuilder eb=new EmployeeBuilder();
2. Employee e=eb.addName("kamal").addAdd("dcd").addDoj("45").build();
3. System.out.println(e);
4. PersonBuilder pb=new PersonBuilder();
5. Person p=pb.addName("Kamal").addAdd("dlf").build();
6. System.out.println(p);
}
}
I have two questions to ask in these lines of code. The lines of code are related to the Fluent(design pattern) Recursive Generics. First is as Line 1, 2, 3 are running that means the Return type of PersonBuilder method is EmployeeBuilder, but I have also studied that the type erasure replaces the type with the bounds, So it should be replacing with PersonBuilder(EmployeeBuilder) and the program should not be running. Because when in case of generics the input parameters of a function will be decided by the type Erasure. The other question is what type Erasure is going to do for the line Number 4,5,6. Can anyone explain?
Output:
Employee{name='kamal', add='dcd', doj='45'}
Person{name='Kamal', add='dlf'}
Aucun commentaire:
Enregistrer un commentaire