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

前端 未结 19 2257
灰色年华
灰色年华 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:34

    If a variable is defined as public static it can be accessed via its class name from any class.

    Usually functions are defined as public static which can be accessed just by calling the implementing class name.

    A very good example of it is the sleep() method in Thread class

    Thread.sleep(2500);
    

    If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you). The difference between private var_name and private static var_name is that private static variables can be accessed only by static methods of the class while private variables can be accessed by any method of that class(except static methods)

    A very good example of it is while defining database connections or constants which require declaring variable as private static .

    Another common example is

    private static int numberOfCars=10;
    
    public static int returnNumber(){
    
    return numberOfCars;
    
    }
    

提交回复
热议问题