I just start out with an example, that explains it best:
public abstract class A{
static String str;
}
public class B extends A{
public B(){
only one instance of static variable is present in the system.
static variable will load into the system in the start before class is loaded.
reason both time abc is printed is because you set the value of str as abc in the last.
It is what I did to avoid to have to implement the same method in every subclass. It is based on the answer of Bozho. Maybe it may help someone.
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Uglylab
*/
public class SandBox {
public static void main(String[] args) {
A b = new B();
A c = new C();
System.out.println("b.str = " + B.getStr(b.getClass()));
System.out.println("c.str = " + C.getStr(c.getClass()));
}
}
abstract class A{
protected static Map<Class, String> values = new HashMap<>();
public static String getStr(Class<? extends A> aClass) {
return values.get(aClass);
}
public static void setStr(Class<? extends A> aClass, String s) {
values.put(aClass, s);
}
}
class B extends A{
public B(){
setStr(this.getClass(),"123");
}
}
class C extends A{
public C(){
setStr(this.getClass(),"abc");
}
}