我有以下旧代码,如下所示。我想知道在设置BikeGroup时是否可以设置BikeName和BikeModel?基本上,当用户设置BikeGroup时,我们如何自动设置Foo的BikeName和BikeModel版本?无需使用构造函数来设置值。我正在使用Validator(spring框架)设置BikeGroup ...因此我无法使用构造函数或setter来设置值。
Class Foo{
private BikeGroup; // 1. when this is set
private String bikeName; // 2. set this with value in BikeGroup
private String bikeModel; // 3. and set this with value in BikeGroup
//getters/setters
}
Class BikeGroup{
private String bikeName;
private String bikeModel;
//getters/setters
}
答案 0 :(得分:1)
是的。 但是,Foo
的构造函数必须命名为Foo
(并且您想将BikeGroup
传递给该构造函数,因此需要一个参数)。而且您不要将()
放在class
声明中。像
class Foo {
public Foo(BikeGroup bg) {
this.bikeName = bg.getBikeName();
this.bikeModel = bg.getBikeModel();
}
private String bikeName;
private String bikeModel;
}
或,使用设置器...
class Foo {
public void setBikeGroup(BikeGroup bg) {
this.bikeName = bg.getBikeName();
this.bikeModel = bg.getBikeModel();
}
private String bikeName;
private String bikeModel;
}