Junior — Middle
Can you explain what is meant by a telescopic constructor?
sobes.tech AI
Answer from AI
A telescopic constructor is a design pattern in Java where a class has multiple constructors with different numbers of parameters, and each constructor calls the next constructor with more parameters, passing default values for missing arguments. This approach allows creating objects with different sets of parameters but can lead to bulky and hard-to-read code when there are many parameters.
Example:
public class NutritionFacts {
private final int servingSize; // required
private final int servings; // required
private final int calories; // optional
private final int fat; // optional
public 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 = servingSize;
this.servings = servings;
this.calories = calories;
this.fat = fat;
}
}
This approach is convenient for a small number of parameters, but as the number of parameters increases, it is better to use the "Builder" pattern.