Why is it said that static can be used without static in java?

From a code flexibility perspective : 使用static关键字会使代码变得更加僵化because it binds methods or variables to classes rather than instances. This means they cannot be overridden or overridden by subclasses.

From a testability perspective : 静态方法和变量往往很难进行单元测试, because they rely on the class itself, not the instance. This makes testing and simulation difficult.

From a scalability perspective : 使用静态方法和变量会限制代码的可扩展性. If static methods or variables need to be changed or extended in other parts of the program, the entire code base may need to be modified.

From a thread safety perspective : 静态方法和变量在多线程环境中可能会引发并发问题. Multiple threads accessing or modifying static variables at the same time may cause thread safety issues.

From the perspective of memory management : 由于使用static进行修饰的变量或者方法会常驻内存并且伴随整个生命周期Therefore, if the number of variables modified by static is large, it will occupy a large amount of memory space , which may cause insufficient memory and affect the performance of the system . If the variables are not released correctly or the garbage collection mechanism cannot Recycling will cause memory leaks. Since variables always exist in memory, if the value of the variable changes at a certain point in time, other parts of the code cannot obtain the latest value of the variable, resulting in logic errors.

Since there are some limitations and potential problems with using static methods and variables , in Java it is better to use instance methods and variables if you can avoid using statics . But in some cases,静态方法和变量仍然是有用的,比如工具类或常量等。

Guess you like

Origin blog.csdn.net/m0_64365419/article/details/133417780