简体   繁体   中英

Static variable in an abstract generic class

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM