Are global static classes and methods bad?

前端 未结 10 1300
予麋鹿
予麋鹿 2020-12-02 13:36

It\'s generally agreed upon that relying heavily on global stuff is to be avoided. Wouldn\'t using static classes and methods be the same thing?

10条回答
  •  我在风中等你
    2020-12-02 14:06

    public class Foo
    {
        private static int counter = 0;
    
        public static int getCounterValue()
        {
             return counter;
        }
        //...
        public Foo()
        {
            //other tasks
            counter++;
        }
    }
    

    In the code above you can see that we count how many Foo objects were created. This can be useful in many cases.

    The static keyword is not global, it's telling you that it's on class level, which can be very useful in various cases. So, in conclusion, class level things are static, object level things are not static.

提交回复
热议问题