这是一个非常简单的问题。我正在为我的应用程序创建一个简单的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值为true,则使用一个构造函数,如果为false,则使用其他构造函数。我怎么能这样做?
答案 0 :(得分:1)
创建一个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