running the Demo class will invoke a static method newInstance in SomeClass to call the constructor and printing hello
defining a method will include a return type + method name with arguments
the return type for newInstance is <T>SomeClass<T> seems weird to me since my class is called SomeClass<T> instead of <T>SomeClass<T>
why do i need the <T> in front of the SomeClass<T> ? it seems that if I don't include it there will be an common error called Cannot make a static reference to the non-static type T
another thing to point out is that I can put many spaces between <T> and SomeClass<T> so it doesn't seem like they need to be together.
public class SomeClass<T> {
public static <T>SomeClass<T> newInstance(Class<T> clazz){
return new SomeClass<T>(clazz);
}
private SomeClass(Class<T> clazz){
System.out.println("hello");
}
}
public class Demo {
public static void main(String args[])
{
SomeClass<String> instance = SomeClass.newInstance(String.class);
}
}
Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.
You cannot refer non-static members from a static method. Non-Static members (like your fxn(int y)) can be called only from an instance of your class. or you can declare you method as static. Save this answer.
What is a static method? A Method that works on the class, and not a specific instance. The generic parameter T
in the class signature public class SomeClass<T>
is only available for a specific instance (hence non-static type T
). e.g. SomeClass<String>
where the [T = String]
.
By including <T>
in the method signature of public static <T>SomeClass<T> newInstance(Class<T> clazz)
. You're saying that; for this method, there is a generic type argument T
. This T
is separate from the T
in the class signature. So it might as well be C
i.e. public static <C> SomeClass<C> newInstance(Class<C> clazz)
. Or something completely different.
But if you don't include <T>
with the method, the compiler thinks you're trying to use the T
in the class signature. Which is illegal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With