class classname {
private int value;
public classname(int value) {
if(value > 20 || value < 1) {
//make object null
}
else {
this.value = value;
}
}
}
基本上,当参数不在我想要制作空对象的范围内时。
类似的东西:
classname newclass = new classname(100);
if(newclass == null) {
//this is what i want
}
答案 0 :(得分:2)
不应使用object
初始化null
,而应抛出IllegalArgumentException
,例如:
if(value > 20 || value < 1) {
throw new IllegalArgumentException("Value must be between 1 and 20");
}
这将阻止初始化并向用户返回正确的错误消息。此外,这被视为最佳做法(例如,尝试调用Integer.parseInt("abc");
)
答案 1 :(得分:1)
了解工厂设计。您应该创建一个工厂类,并让该工厂返回类实例。在工厂内部实现中,您可以根据参数编写逻辑。
看看这篇文章。 Create Instance of different Object Based on parameter passed to function using C#
答案 2 :(得分:1)
您应该创建一个工厂方法,如果参数有效或返回null,则返回实例,并使用private
隐藏构造函数:
class YourClass {
private int value;
// Factory method
public static YourClass newYourClass(int value) {
if(value > 20 || value < 1)
return null;
else
return new YourClass(value);
}
private YourClass(int value) {
this.value = value;
}
}
答案 3 :(得分:0)
你可以做这样的事情
class classname {
private Integer value;
public classname(Integer value) {
this.value = value <1 || value>20 ? null : value;
}
}
答案 4 :(得分:0)
你可以这样做
public class MyClass {
private int value; // if -1 not in the range!
public MyClass(int value) {
if (value > 20 || value < 1) {
this.value = -1;
} else {
this.value = value;
}
} //end of constructor
} //end of the MyClass
答案 5 :(得分:0)
public class CustomObjectFactory
{
private int value;
CustomObjectFactory(int value)
{
this.value = value;
}
public CustomObjectFactory getInstance()
{
System.out.print(value);
if(value<10)
{
System.out.print("if"+value);
return null;
}else
{
System.out.print("else"+value);
return new CustomObjectFactory(value);
}
}
}