Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

guava: why methods create() instead of constructor?

Please, can you explain why the creators of guava prefer to define the constructors as private, and to define static methods create() to create objects ?

like image 568
Laloi Avatar asked Nov 03 '12 17:11

Laloi


1 Answers

Effective Java item 1: Consider static factory methods instead of constructors.

Some of the advantages of static factory methods include:

  • They automatically infer type parameters pre-Java 7.
  • They allow us to control inheritance patterns: we can subclass collection types within Guava without letting outside code subclass them.
  • They let us return an arbitrary subclass of the desired type, letting us hide implementation details better.
like image 200
Louis Wasserman Avatar answered Sep 17 '22 15:09

Louis Wasserman