问题
I have a class called cache. It is an generic, abstract class responsible for handling the global cache for forever type extends the class. My question is, if I have a static variable under the base class, will the static variable be unique per extending type or will it be the same for all types that extend Cache.
For example the interface:
Cache<K, V>
private static Cache<K, V>
[creates a cache store on first load]
static V get(K key);
Then I have an implementing class:
PersonCache extends Cache<String, Person>
void load(String person);
JobCache extends Cache<Integer, Job>
void load(Integer key);
Which behavior will be expected from Cache's static variable. [The get variable's intention is to be a single public entry point to the JobCache/PersonCache's store] will each type (PersonCache, JobCache] have its own cache store, or will Cache try to store everything it receives?
回答1:
I don't think you can do that. From the Java Language Specification Sec. 8.1.2:
It is a compile-time error to refer to a type parameter of a class C anywhere in the declaration of a static member of C or the declaration of a static member of any type declaration nested within C. It is a compile-time error to refer to a type parameter of a class C within a static initializer of C or any class nested within C.
回答2:
The private static Cache
variable will be stored once against the Cache
class, and none of the sub-classes.
The function of your [creates a cache store on first load]
will have to decide which sub-class to instantiate. This method will be static so cannot be overridden.
If you're looking to implement the singleton pattern you should note that it's not really compatible with inheritance. It also doesn't lend itself to a well tested system.
来源:https://stackoverflow.com/questions/8198443/static-variable-in-an-abstract-generic-class