gpt4 book ai didi

java - 根据 boolean 值制作2个构造函数

转载 作者:行者123 更新时间:2023-11-30 00:52:12 25 4
gpt4 key购买 nike

这是一个非常简单的问题。我正在为我的应用制作一个简单的 Java 对象,如下所示:

public class Category{
// STATE
private String mCategoryName;
private Boolean mContainsSubcategories;
private Subcategory[] mSubcategoryList; // Subcategory is another object
// Constructor
// for mContainsSubcategories == false, use the below constructor
public Category(String categoryName, Boolean containsSubcategories){

}
// for mContainsSubcategories == true, use the below constructor
public Category(String categoryName, Boolean containsSubcategories, Subcategory[] subcategoryList){

}

// GETTER METHODS
/* ..................... */
}

基本上,我想要的是根据 boolean 值使用不同的构造函数。如果 boolean 值为真,则使用一个构造函数,如果为假,则使用另一个构造函数。我该怎么做?

最佳答案

创建一个 getinstance 方法:

public class Category{

// STATE
private String mCategoryName;
private Boolean mContainsSubcategories;
private Subcategory[] mSubcategoryList; // Subcategory is another object
// Constructor
public static Category getInstance(boolean mContainsSubcategories,String mCategoryName, Subcategory[] subcategoryList) {
if (mContainsSubcategories){
return new Category(mCategoryName);
}else {
return new Category(mCategoryName,subcategoryList);
}
}
// for mContainsSubcategories == false, use the below constructor
public Category(String categoryName){

}
// for mContainsSubcategories == true, use the below constructor
public Category(String categoryName, Subcategory[] subcategoryList){

}

// GETTER METHODS
/* ..................... */
}

并初始化它使用:

Category myCategory =    
Category.getInstance(mContainsSubcategories,mCategoryName,subcategoryList);
//instead of new Category

关于java - 根据 boolean 值制作2个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829994/

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