Reputation: 921
I'm reading an article by Brain Goetz. I had a doubt regarding factory method for the below code.
public class BoxImpl<T> implements Box<T> {
public static<V> Box<V> make() {
return new BoxImpl<V>();
}
Author had written this to reduce the redundancy of redeclaration of the type parameters as
Box<String> box=new Box<String>();
So, he used the factory method like above.
Box<String> myBox = BoxImpl.make();
But here my doubt is why <V>
in the make method of the Box
class, why can't we use like below:
public class BoxImpl<T> implements Box<T> {
public static<T> Box<T> make() {
return new BoxImpl<T>();
}
What is the difference between above two ?
Upvotes: 1
Views: 86
Reputation: 20885
This technique (used, among the others, by the Guava collections) was quite useful before the introduction of the diamond operator <> in Java 7, to avoid very noisy code like:
// Java 5:
Box<Map<String, List<Integer>> box = new BoxImpl<Map<String, List<Integer>>();
// with static inference
Box<Map<String, List<Integer>> box = BoxImpl.make();
// with diamond operator - Java7
Box<Map<String, List<Integer>> box = new BoxImpl<>();
As per why declaring a new type parameter V
in the make method, it's because it's static, and static method can't access type arguments because they are out of scope, and belong to a specific instantiation of a type (similar to instance variables, that can't be used in static methods)
Upvotes: 1
Reputation: 213261
Making that method generic is important, because you can't use the type parameter T
of the class in a static
context. So the following code wouldn't compile:
class BoxImpl<T> implements Box<T> {
// Will fail to compile. Cannot use type parameter `T` in static context
public static Box<T> make() {
return new BoxImpl<T>();
}
}
From Java Generics FAQs:
The scope of a class's type parameter is the entire definition of the class, except any static members or static initializers of the class. This means that the type parameters cannot be used in the declaration of static fields or methods or in static nested types or static initializers.
Upvotes: 1
Reputation: 279970
This
public class BoxImpl<T> implements Box<T> {
is a generic class declaration. It declares a type variable T
for use in instance class members.
This
public static<V> Box<V> make() {
return new BoxImpl<V>();
}
is a generic method. It declares its own generic variables and is static
. It cannot use the class type variables.
The name of the type variable is not an issue here. The name could be the same, but it will not be referring to the same type.
Upvotes: 1