gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:19:26 25 4
gpt4 key购买 nike

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

    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*/

最佳答案

您不能调用多个构造函数来创建一个类的一个实例。每次调用都会创建一个与另一个完全不同的新实例。要使用构造函数设置 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);
}

关于java - 多个构造函数初始化一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com