Chapter II Creating and Destroying objects
The first one uses the static factory method instead of the constructor, because:
- Static factory methods can have different names, that is, the constructor can only be distinguished by different parameters, and static factories can express different purposes in their names.
- The static factory method creates a new object without each invocation (in fact because it is static, so it can only be used as static, so it is created early and does not need to be created repeatedly). ), such as boolean.valueof (Boolean) in the book
1 public static final Boolean TRUE = new Boolean (true ); 2 Public static Boolean valueOf (boolean b) { 4 return (b True:false); 5 True and false here are well-established instances that do not need to be created every time the method is called 6 }
- A static factory method can return an object of any primitive type subtype,?????
- Static factory methods, which make the code more concise when creating instances of parameterized types. Like what's in the book.
// Suppose HashMap provides this static factory: Public static <K,V> hashmap<k,v> newinstance () { returnnew hashmap< K,v>();} // Then: map<string,list<string>> m = hashmap.newinstance (); // more concise than the following: New Hashmap<string,list<string>> ();
[Effective Java Reading notes] Chapter II Creating and destroying objects the first article