java - Is overriding static field with static block bad practice? -


i want create data structures capture following ideas:

in game, want have generic skill class captures general information skill id, cool down time, mana cost, etc.

then want have specific skills define actual interaction , behaviours. these extend base class skill.

finally, each player have instances of these specific skills, can check each player's skill status, whether player used recently, etc.

so have abstract superclass skill defines static variables, skills have in common, , each individual skill extends skill, use static block reassign static variables. have following pattern:

class {     static int x = 0; }  class b extends {     static {         x = 1;     } }  ...  // in method b = new b(); system.out.println(b.x); 

the above prints 1, behaviour want. problem system complains i'm accessing static variable in non-static way. of course can't access in way, because want treat skill skill without knowing subclass is. have suppress warning every time this, leads me think whether there better/neater design pattern here.

i have thought making variables in question non-static, because should static across all instances of specific skill, feel should static variable...

you should avoid such use of global state. if know sure field x shared across all instances of all subtypes of base class, correct place put such field somewhere other base class. may in other configuration object.

but current configuration, does't make sense since subclass modifies static variable make variable visible classes. if subclass b changes x 1, subclass c changes 2, new value visible b well.

i think way described in question, every subclass should have own separate static field. , in abstract base class, can define method implemented each subclass in order access each field:

abstract class {      public abstract int getx(); }  class b extends {     public static int x = 1;      public int getx() {         return x;     } }  class c extends {     public static int x = 2;      public int getx() {         return x;     } } 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -