I have two class Parent and Child, where Parent and Child class has one variable with same name.
-> Parent class
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class Parent {
private String parentA;
private String parentB;
private String parentC;
}
-> Child Class
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class Child extends Parent {
private String childA;
private String parentB; //variable name is same as Parent class
private String childC;
}
Now in Main class I am making Child class object by using builder.
public class Main {
public static void main(String Args[]) {
Child child = Child.builder()
.parentA()
.parentB() // Here it is setting Child class variable
.parentC()
.childA()
.childC()
.build();
}
}
Now I want to set parentB variable of parent class. Is there is any way to set it?
@SuperBuilder
generates a method for each field defined in the annotated class, but not for fields from superclasses. Instead, the generated builder class extends
the builder class of the superclass, so the methods for fields from superclasses are inherited from those builders.
If you have two exactly similar fields in Parent
and Child
, the method from ChildBuilder
simply overrides the method from ParentBuilder
. There is no way to call the method from ParentBuilder
anymore (except for some ugly MethodHandle
hacks, which you should not do).
Remark: Having two identical fields indicates that they have similar meaning. If this is the case, make one protected
and remove the other. If they do not have the same meaning, naming them equally is a very bad idea and will almost certainly lead to bugs even if you do not use @SuperBuilder
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.