4

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.

jmj
  • 237,923
  • 42
  • 401
  • 438
Saturn
  • 17,888
  • 49
  • 145
  • 271

3 Answers3

15

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
5

Well that would not be possible simply because a Constructor is simply meant to set stable state to the object which can be safely used later. In short, once the object is initialized, constructor is useful to set the internal state. So returning anything makes no sense.

What you can indeed do is have a public static method which can create the object for you. Something like:

public class Container {
    private static Container cachedContainer = new Container(5);
    private int number;
    public Container(int number) {
        this.number = number;
    }

   public static Container getContainer(int number, boolean check){
     if (number == 5 && check) {
        return cachedContainer;   
    } else return new Container(number);
}
Jatin
  • 31,116
  • 15
  • 98
  • 163
1

You need something like this:

public class Container {
    private static final Container CACHED_CONTAINER = new Container(5);
    private final int number;

    private Container(final int number) {
        this.number = number;
    }

    public static Container container(final int num, final boolean check) {
        if (num == 5 && check) {
            return CACHED_CONTAINER;
        }
        return new Container(num);
    }
}