gpt4 book ai didi

java - 构造函数不能返回新实例吗?

转载 作者:行者123 更新时间:2023-12-02 10:47:56 24 4
gpt4 key购买 nike

是否可以让构造函数根据参数决定不创建新实例?例如:

public class Foo{

public Foo(int n){

if(n<0){
//DO NOT make this
}
else{
//Go ahead and make this instance
}
}
}

我知道这是不可能的:

 public class Foo{

public Foo(int n){

if(n<0){
//DO NOT make this
this = null;
}
else{
//Go ahead and make this instance
}
}
}

有没有办法正确地做同样的事情?

最佳答案

构造函数无法控制返回的内容。但是,您可以使用静态工厂方法以获得更大的灵 active :

public static Foo newInstance(int n) {
if (n < 0) {
return null;
} else {
return new Foo(n);
}
}

当提供的数字无效时,抛出异常比返回 null 更好:

if (n < 0) {
throw new IllegalArgumentException("Expected non-negative number");
} ...

关于java - 构造函数不能返回新实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28265059/

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