多个构造函数初始化一个对象

时间:2014-10-28 17:59:23

标签: java

我很想知道你是否可以调用多个构造函数并通过它们初始化一个对象值。我一直在寻找答案,但我没有找到答案;让我告诉你一些代码并提前感谢你的帮助:

    int MAX_VALUE; // Field variable
    boolean[] elements = new boolean[10000]; // Field variable

    public IntegerSet(int maxValue) {
        this.MAX_VALUE = maxValue;
    }
    public IntegerSet(boolean[] tmp) {
        int i = 0;

        for(i = 0; i < tmp.length; ++i)
            this.elements[i] = tmp[i];

        this.elements = Arrays.copyOf(this.elements, tmp.length);
    }

/*In main:*/

    // I just want to have one object, s1, and I want to be able
    // to access MAX_VALUE and elements by s1.MAX_VALUE and s1.elements
    IntegerSet s1 = new IntegerSet(50); 
    /* SOMETHING that uses second constructor with object s1*/

1 个答案:

答案 0 :(得分:2)

您不能调用多个构造函数来创建一个类的实例。每次调用都会创建一个与另一个完全不同的新实例。要使用构造函数设置int字段和数组,应将值传递给构造函数本身:

public IntegerSet(boolean[] tmp, int maxValue) {
    this.MAX_VALUE = maxValue;
    int i = 0;

    for(i = 0; i < tmp.length; ++i)
        this.elements[i] = tmp[i];

    this.elements = Arrays.copyOf(this.elements, tmp.length);
}

这相当于

public IntegerSet(boolean[] tmp, int maxValue) {
    this(maxValue);   // will call the constructor that takes one parameter
    int i = 0;

    for(i = 0; i < tmp.length; ++i)
        this.elements[i] = tmp[i];

    this.elements = Arrays.copyOf(this.elements, tmp.length);
}