static 변수를 클래스마다 상속하기.

템플릿을 사용한 클래스별 static 변수의 상속

I made an ugly code to solve the problem in JAVA. (Not to metion of instantiation. I know. I’ve violated the rule.)

Better Idea?

BTW, you should not use Thread.currentThread() or populate exception by your self. They are very sl~~~ow methods in Java. So, do not use them in this problem.

No singleton. Just subclassing is allowed.

I guess there is no way in JAVA if I can not use Thread.currentThread() or exception.

———————————-


import java.util.*;
public class StaticForEachClass {
    
    private static Hashtable<Class<? extends StaticForEachClass>, 
        Integer> fStaticVarTable
        = new Hashtable<Class<? extends StaticForEachClass>, 
            Integer>();

    public void setValue(int v) {
        fStaticVarTable.put(getClass(), v);
    }
    
    public int getValue() {
        return fStaticVarTable.get(getClass());
    }
}


class A extends StaticForEachClass {
    
    
}


class B extends StaticForEachClass {
    
}

class App {
    public static void main(String[] args) {
        
        A a = new A();
        a.setValue(1);
        System.out.println("A.getValue(): " + a.getValue());
        
        B b = new B();
        b.setValue(2);
        System.out.println("B.getValue(): " + b.getValue());
        System.out.println("A.getValue(): " + a.getValue());
    }
}

Similar Posts:

Comments 2