Java: static field in abstract class

后端 未结 8 1065
独厮守ぢ
独厮守ぢ 2020-12-24 01:04

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(){
                


        
相关标签:
8条回答
  • 2020-12-24 01:32

    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.

    0 讨论(0)
  • 2020-12-24 01:37

    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");
        }
    }
    
    0 讨论(0)
提交回复
热议问题