Search code examples
javafactory-patternpublic-method

public static factory method


First of all please forgive me if its a really dumb question, I am just trying to learn this language to its core. I am reading Effective Java and the very first chapter talks about Static factory methods vs. Constructors. Their pros and cons. Few things that are confusing to me are:

  1. class of an object returned by static factory method is nonpublic - what exactly does it mean?
  2. unlike constructors static factory methods are not required to create a new object each time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?

Thanks.


Solution

  • class of an object returned by static factory method is nonpublic - what exactly does it mean?

    It means that the actual class of the objects returned by a static factory method can be a subclass of the declared type, and this subclass does not have to be public. It's just another implementation detail that client code should not care about.

    unlike constructors static factory methods are not required to create a new object each > time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?

    Yes, that's one way this could be done. But really, anything is possible.