class Formulas{
private double x=0, y=0, z=0, t=0, theta=0, v=0, a=0;
}
Run Code Online (Sandbox Code Playgroud)
假设我有一个类似于上面的类,并且想要为给定字段的所有可能组合重载构造函数.有没有更快的方法来使用Eclipse生成所有必需的构造函数?
考虑两个可能的构造函数:
public Formulas(double x);
public Formulas(double theta);
它们具有相同的签名,因此最终编译器无法区分它们,因此这是非法的.
简短的回答是它无法完成.请考虑使用Builder或Factory模式.
你也可以"分而治之"的论点.我不确定你的v和a是什么,但是,如果它们是与theta相关的角度值,你可以使用Point3D和Angle3D类来保存6个输入,并有一个构造函数
public Formulas(Point3D point, Angle3D angle)
构建器模式更清晰、更易读。
至于“快速方法”,请查看在 Eclipse 中自动创建类的构建器。
public class Formulas {
private double x=0, y=0, z=0, t=0, theta=0, v=0, a=0;
public Formulas() {
}
public Formulas withX(double x) {
this.x = x;
return this;
}
public Formulas withY(double y) {
this.y = y;
return this;
}
// repeat
public double getX() {
return x;
}
public double getY() {
return y;
}
// repeat...
}
Run Code Online (Sandbox Code Playgroud)
用法
public static void main(String[] args) {
Formulas f = new Formulas().withX(2).withY(4);
System.out.printf("%s %s\n", f.getX(), f.getY()); // 2.0 4.0
}
Run Code Online (Sandbox Code Playgroud)