Is it possible in Java to have a constructor return another instance of the class, rather than constructing/returning itself?
Kinda like
public class Container {
private static Container cachedContainer = new Container(5,false);
private int number;
public Container(int number, boolean check) {
if (number == 5 && check) {
return cachedContainer; // <-- This wouldn't work
}
this.number = number;
}
}
In that example, if you create an object containing the number 5 (and use the "check" flag), it will "interrupt" the construction and instead give you a preexisting object that already contains 5. Any other number won't cause such interruption.
No that is where static factory method pattern comes in
You could perform custom calculation and determine whether to create instance or not in static factory method
consider this for your example:
public static Container createContainer(int number, boolean check) {
if (number == 5 && check) {
// returned cached instance
}
// construct new instance and return it
}
From effective java
Item 1: Consider static factory methods instead of constructors
Summary:
Also See
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With