问题
I have a pojo which contains a set of private variables and their setters and getters. This pojo is used extensively across my application. Now, I have to support a scenario where there are multiple pojos and each pojo is a superset of the initial pojo I have. Is it possible that I can extend my original pojo so that I need not change my existing business logic. I am new to spring and I dont know if this is possible. Pojo B should contain everything in pojo A and few more things. Inside the code I will create pojo B objects through pojo A. Basically, some thing similar to inheritance, but with pojos.
回答1:
Typically, you would either aggregate or inherit.
Inherit:
class A {
private String name;
public String getName() {
return name;
}
}
class B extends A {
}
Aggregate
public interface A {
public String getName();
}
public class AImpl implements A {
private String name;
public String getName() {
return name;
}
}
public class BImpl implements A {
private A wrapped;
public BImpl(A wrapped) {
this.wrapped = wrapped;
}
public String getName() {
return wrapped.getName();
}
}
来源:https://stackoverflow.com/questions/9390581/is-it-possible-to-extend-a-pojo-class-in-spring