-2

Most of my experience with Java has been in the classroom setting, editing my own code. I'm finally venturing into the exciting world of deciphering other people's code, and I'm wondering about this:

public class MyClass {

    // Some fields here
    // A constructor there
    // Setters and getters abound

    public static MyClass create() {
        return new MyClass();
    }
}

I'm wondering what the purpose of this method is. It doesn't seem like more trouble to write MyClass foo = new MyClass(); than to write MyClass foo = MyClass.create();. Is this some kind of Java idiom I'm unaware of? Is it completely unnecessary? Would it perhaps be somehow more useful in a class where the constructor took any parameters? What's the deal?

Thanks!

Mike S
  • 1,451
  • 1
  • 16
  • 34

2 Answers2

0

It's a very useful idiom, static factory method. It gives full control on the new instance creation, whether it's a different instance, a cached instance etc. It only makes sense if the constructor is set to private.

public class MyClass {

  private MyClass() {}

  public static MyClass create() {
      return new MyOtherClass();
  }

  private static class MyOtherClass extends MyClass {
    ...
  }
}
karakfa
  • 66,216
  • 7
  • 41
  • 56
  • *It only makes sense if the constructor is set to private.* Why do you say that? – shmosel Nov 16 '17 at 01:53
  • If not, you don't have full control of the instance creation which is the primary reason. – karakfa Nov 16 '17 at 01:54
  • 2
    Not really. Factory methods can offer additional functionality and clarity, but that doesn't mean you have to restrict access to the constructors. It's common to have both in Joda, for example. – shmosel Nov 16 '17 at 01:57
-1

Static factory method.

The constructor is normally private, that way the creation of new objects can be controlled by one method.

Further reading static builder class.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311