提供一个只有必要参数的构造器,第二个构造器有一个可选参数,第三个构造器有两个可选参数,以此类推,最后一个构造器包含所有的可选参数。参数少的构造器调用参数多的构造器创建。public class NutritionFacts {private final int servingSize; //(ml) requiredprivate final int servings; //(per container) requiredprivate final int calories; // optionalprivate final int fat; //(g) optionalprivate final int sodium; //(mg) optionalprivate final int carbohydrate; //(g) optionalpublic NutritionFacts(int servingSize,int servings){ //必须的选项this(servingSize,servings,0);}public NutritionFacts(int servingSize,int servings,int calories){this(servingSize,servings,calories,0);}public NutritionFacts(int servingSize,int servings,int calories,int fat){this(servingSize,servings,calories,fat,0);}public NutritionFacts(int servingSize,int servings,int calories,int fat,int sodium){this(servingSize,servings,calories,fat,sodium,0);}public NutritionFacts(int servingSize,int servings,int calories,int fat,int sodium,int carbohydrate){ //包含所有的选项
设计技巧19:重叠构造器 Telescoping Constructor 对多个参数实例的构造器提供支持
最新推荐文章于 2021-09-18 18:38:40 发布