I want to define a time interface like that:
public interface TimeInterface
{
static T ZERO;
static T INFINITY;
// some other methods...
}
Is this possible, or how to do that to avoid errors?
Thanks in advance!
解决方案
From the javadoc directly:
We cannot declare static fields whose types are type parameters
A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed. Consider the following class:
public class MobileDevice {
private static T os;
// ...
}
If static fields of type parameters were allowed, then the following code would be confused:
MobileDevice phone = new MobileDevice<>();
MobileDevice pager = new MobileDevice<>();
MobileDevice pc = new MobileDevice<>();
Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It cannot be Smartphone, Pager, and TabletPC at the same time. You cannot, therefore, create static fields of type parameters.