在Java中,构造函数不能直接返回值。但是,可以通过以下方法来实现从类中返回2个值的构造函数:
public class MyClass {
private int value1;
private int value2;
public MyClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int getValue1() {
return value1;
}
public int getValue2() {
return value2;
}
}
public class MyClass {
private int value1;
private int value2;
public MyClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int getValue1() {
return value1;
}
public int getValue2() {
return value2;
}
}
public class Main {
public static void main(String[] args) {
MyClass myObject = new MyClass(10, 20);
int value1 = myObject.getValue1();
int value2 = myObject.getValue2();
System.out.println("Value 1: " + value1);
System.out.println("Value 2: " + value2);
}
}
输出结果:
Value 1: 10
Value 2: 20
这样就实现了从类中返回2个值的构造函数。