Recently I\'ve faced a question : How to avoid instantiating a Java class?
However, I answered by saying:
If you don\'t want to instantiate
Four reasons spring to mind:
As an example of (2), you may want to create canonical objects. For example, RGB color combinations. You don't want to create more than one instance of any RGB combo so you do this:
public class MyColor {
private final int red, green, blue;
private MyColor(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public static MyColor getInstance(int red, int green, int blue) {
// if combo already exists, return it, otherwise create new instance
}
}
Note: no no-arg constructor is required because another constructor is explicitly defined.