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

前端 未结 19 2256
灰色年华
灰色年华 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条回答
  •  旧时难觅i
    2020-12-02 04:17

    In the following example, eye is changed by PersonB, while leg stays the same. This is because a private variable makes a copy of itself to the method, so that its original value stays the same; while a private static value only has one copy for all the methods to share, so editing its value will change its original value.

    public class test {
    private static int eye=2;
    private int leg=3;
    
    public test (int eyes, int legs){
        eye = eyes;
        leg=leg;
    }
    
    public test (){
    }
    
    public void print(){
        System.out.println(eye);
        System.out.println(leg);
    }
    
    public static void main(String[] args){
        test PersonA = new test();      
        test PersonB = new test(14,8);
        PersonA.print();    
    }
    

    }

    > 14 3

提交回复
热议问题