Irrespective of final keyword the single static variable won't work for multiple sub class due to single static variable get reassigned whenever new subclass is instantiated. Also the order of instantiation will still confuse further on what value lastly updated statically.
jshell> public abstract class A { public static String STATIC_SUPER_VAR = "A"; }
| created class A
jshell> public class B extends A { public B() { STATIC_SUPER_VAR = "B"; } }
| created class B
jshell> B.STATIC_SUPER_VAR
$3 ==> "A"
jshell> A.STATIC_SUPER_VAR
$4 ==> "A"
jshell> new B()
$3 ==> B@685cb137
jshell> B.STATIC_SUPER_VAR
$4 ==> "B"
jshell> A.STATIC_SUPER_VAR
$5 ==> "B"
jshell> public class C extends A { public C() { STATIC_SUPER_VAR = "C";} }
| created class C
jshell> new C()
$7 ==> C@5f2108b5
jshell> A.STATIC_SUPER_VAR
$8 ==> "C"
jshell> B.STATIC_SUPER_VAR
$9 ==> "C"
jshell> C.STATIC_SUPER_VAR
$10 ==> "C"
Solution
We can use static Map instead of single static variable.
jshell> public abstract class A {
...>
...> private static Map<Class<? extends A>, Integer> CLASS_FIELD_HOLDER = new HashMap<>();
...>
...> public A (int classSpecificInteger) {
...>
...> CLASS_FIELD_HOLDER.put(getClass(), classSpecificInteger);
...> }
...>
...>
...> public static int getClassSpecificInteger(Class<? extends A> clazz) {
...>
...> return CLASS_FIELD_HOLDER.get(clazz);
...> }
...> }
| created class A
jshell> public class B extends A {
...>
...> public B (int classSpecificInteger) {
...>
...> super(classSpecificInteger);
...> }
...> }
| created class B
jshell> public class C extends A {
...>
...> public C (int classSpecificInteger) {
...>
...> super(classSpecificInteger);
...> }
...> }
| created class C
Ensure sub class is initialised, I mean Static Map is updated before access,
Else NPE
jshell> B.getClassSpecificInteger(B.class)
| Exception java.lang.NullPointerException
| at A.getClassSpecificInteger (#5:13)
| at (#7:1)
Initialised now:
jshell> new B(10);
$8 ==> B@610694f1
jshell> new C(20)
$9 ==> C@50b494a6
Access it now statically, without having FIELD in the subclass:
jshell> B.getClassSpecificInteger(B.class)
$10 ==> 10
jshell> A.getClassSpecificInteger(B.class)
$11 ==> 10
jshell> B.getClassSpecificInteger(C.class)
$12 ==> 20