Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Java to have a constructor return another instance of the class, rather than constructing/returning itself?

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.

like image 578
Voldemort Avatar asked Nov 30 '22 11:11

Voldemort


1 Answers

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:

  • it can have name to make clear communication with client
  • you could perform custom logic and don't have to create instance every time
  • you could return a subtype

Also See

  • How to create a Class with multiple constructors that use the same parameter type
like image 148
jmj Avatar answered Dec 04 '22 12:12

jmj