【问题标题】:Calling the proper constructor based on input length根据输入长度调用正确的构造函数
【发布时间】:2014-05-28 15:40:20
【问题描述】:

我有一个Point 课程。

该点既可以是 2-D 也可以是 3-D。我是根据传递给构造函数的坐标数组的长度来决定的。

    double x, y, z;
    int dimension;
    Point(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
        dimension = 3;
    }
    Point(double x, double y) {
        this.x = x;
        this.y = y;
        this.z = 0;
        dimension = 2;
    }
    Point(double[] p)
    {
        if(p.length == 2)
            this(p[0], p[1]);
        else if(p.length == 3)
            this(p[0], p[1], p[2]);
    }

最后一个构造函数出错,因为构造函数调用必须是构造函数中的第一个语句。

有没有办法实现我正在做的事情?

【问题讨论】:

  • 为什么不创建一个工厂方法呢?

标签: java constructor compiler-errors


【解决方案1】:

也许你可以做类似的事情

double x, y, z;
int dimension;
Test(double x, double y, double z) {
    initDim(x, y, z);
}
Test(double x, double y) {
    initDim(x, y);
}
Test(double[] p)
{
    if(p.length == 2)
        initDim(p[0], p[1]);
    else if(p.length == 3)
        initDim(p[0], p[1], p[2]);
}
private void initDim(double x, double y, double z) {
    this.x = x;
    this.y = y;
    this.z = z;
    dimension = 3;
}

private void initDim(double x, double y) {
    initDim(x, y, 0);
    dimension = 2;
}

【讨论】:

  • 这是一个完美的主意。谢谢!
  • @Sajan 我认为从initDim(double x, double y) 你可以通过传递0 作为最后一个参数来调用initDim(double x, double y, double z)。只是为了避免重复代码。
【解决方案2】:

除了那些我想提出这样的解决方案的人。更少的构造函数且易于适应。有点类似于您创建单例的操作。

public class Point {
    double x, y, z;
    int dimension;

    private Point(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
        dimension = 3;
    }

    private Point(double x, double y) {
        this.x = x;
        this.y = y;
        this.z = 0;
        dimension = 2;
    }

    public Point getInstance(double x, double y, double z) {
        return new Point(x, y, z);
    }

    public Point getInstance(double x, double y) {
        return new Point(x, y);
    }

    public Point getInstance(double[] p) {
        if (p.length == 2)
            return new Point(p[0], p[1]);
        else (p.length == 3)
            return new Point(p[0], p[1], p[2]);         
    }
}

你可以像这样创建你的实例。

Point point = Point.getInstance(0, 0);

【讨论】:

    【解决方案3】:

    构造函数太多通常不好。它为您提供了一个很好的机会来表达应该如何使用它。

    public static Point Create(double... p)
    {
        if(p.length == 2)
            return Point(p[0], p[1]);
        else if(p.length == 3)
            return Point(p[0], p[1], p[2]);
    
        // default case or throw error
    }
    

    或者,您可以创建一个 initialize 方法,您可以从构造函数中调用该方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多