2011年6月15日 星期三

Java static

Advantage of static factory methods:

1. Unlike constructors, they have names.

2. Unlike constructors, they are not required to create a new object each time they're invoked.

3. Unlike constructors, they can return an object of any subtype of their return type.

4. They reduce the verbosity of creating parameterized type instances.
For example :

平常如果要宣告Map類要 :
Map< String, List> m = new HashMap< String, List>();

如果HashMap中有提供這個function, type inference : (實際上沒有,這只是舉例)

public static < k,v
> HashMap< k,v > newInstance() {
return new HashMap< k,v >(); }

那麼要宣告Map就可以改寫成 : Map< String, List> m = HashMap.newInstance();

----------------------------------------------------

Disadvantage
:

1. classes without public or protected constructors cannot be subclassed.

2. They are not readily distinguishable from other static methods.

沒有留言:

張貼留言