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

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

    What is the use of a private static class variable?

    Let's say you have a library book Class. Each time you create a new Book, you want to assign it a unique id. One way is to simply start at 0 and increment the id number. But, how do all the other books know the last created id number? Simple, save it as a static variable. Do patrons need to know that the actual internal id number is for each book? No. That information is private.

    public class Book {
        private static int numBooks = 0;
        private int id;
        public String name;
    
        Book(String name) {
            id = numBooks++;
            this.name = name;
        }
    }
    

    This is a contrived example, but I'm sure you can easily think of cases where you'd want all class instances to have access to common information that should be kept private from everyone else. Or even if you can't, it is good programming practice to make things as private as possible. What if you accidentally made that numBooks field public, even though Book users were not supposed to do anything with it. Then someone could change the number of Books without creating a new Book.

    Very sneaky!

提交回复
热议问题