构造函数重载相同的参数

Edi*_*nda 0 java constructor overloading

假设我有2个字段的类:x和y,类型double.是否可以定义2个构造函数,因此constructor1将创建对象,将其x属性设置为构造函数中的哪个参数告诉y默认值,构造函数2反之亦然?

public class Test {

    private int x;
    private int y;

    public Test(int x) {
        this.x = x;
    }

    public Test(int y) {
        this.y = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试这样的东西,我知道它因为超载规则而无法工作

Jon*_*eet 8

不,你做不到.通常你会做类似的事情:

private Test(int x, int y) {
    this.x = x;
    this.y = y;
}

public static Test fromX(int x) {
    return new Test(x, 0);
}

public static Test fromY(int y) {
    return new Test(0, y);
}
Run Code Online (Sandbox Code Playgroud)

您可能想要考虑这种模式(公共静态工厂方法,它们反过来调用私有构造函数),即使您没有重载问题 - 它也清楚地说明了您传递的值的含义是什么意思.