What is the use of a private static variable in Java?

前端 未结 19 2263
灰色年华
灰色年华 2020-12-02 03:47

If a variable is declared as public static varName;, then I can access it from anywhere as ClassName.varName. I am also aware that static members a

19条回答
  •  感情败类
    2020-12-02 04:30

    private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.

    public class PrivateStatic {
    
    private static int var = 10;
    public void setVar(int newVal) {
        var = newVal;
    }
    
    public int getVar() {
        return var;
    }
    
    public static void main(String... args) {
        PrivateStatic p1 = new Sub1();
        System.out.println(PrivateStatic.var);
        p1.setVar(200);
    
        PrivateStatic p2 = new Sub2();
        System.out.println(p2.getVar());
    }
    }
    
    
    class Sub1 extends PrivateStatic {
    
    }
    
    class Sub2 extends PrivateStatic {
    }
    

提交回复
热议问题