何时使用静态方法和字段? [英] When to use static method and field?

查看:95
本文介绍了何时使用静态方法和字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道静态是什么,但不知道何时使用它。

I know what static is, but just not sure when to use it.

静态变量:
我只将它用于常量字段。有时类中有几十个常量,因此使用静态常量可以节省大量内存。还有其他典型的用例吗?

static variable: I only used it for constant fields. Sometimes there are tens of constants in a class, so using static constants can save lots of memory. Is there any other typical use cases?

静态方法:
我在制作关于算法的课时使用它。例如,提供不同排序算法的类。它是否反对OOP设计?我认为保持这种方式更好,而不是在每个需要使用它们的类中实现排序算法。我错了吗?什么是一些好用例?

static method: I use it when I make a class about algorithms. For example, a class which provides different sorting algorithms. Is it against OOP design? I think it is better to maintain this way rather than implementing sorting algorithms inside each class that needs to use them. Am I wrong? What are some good use cases?

此外,使用静态和非静态字段/方法之间是否有任何性能差异?

Also, are there any performance difference between using static and non-static fields/methods?

推荐答案

您正在描述使用静态的情况,但这并不能从根本上解释为什么要使用静态和非静态 - 它们不仅仅是关键字对于常量和实用方法。

You are describing cases where you've used static, but this doesn't quite explain fundamentally why you would use static vs non-static - they are more than just keywords for constants and utility methods.

当某些东西不是静态的(实例)时,它意味着每个类的实例都有一个实例。每个人都可以独立改变。

When something is not static (instance), it means that there is an instance of it for each instance of the class. Each one can change independently.

当某些东西是静态的时,意味着该类的所有实例只有一个副本,因此从任何位置更改它都会影响所有其他。

When something is static, it means there is only one copy of it for all instances of the class, so changing it from any location affects all others.

静态变量/方法通常使用较少的内存,因为它们只有一个副本,无论您拥有多少个类实例。静态,如果使用得当,在面向对象设计中完全没问题。

Static variables/methods typically use less memory because there is only one copy of them, regardless of how many instances of the class you have. Statics, when used appropriately, are perfectly fine in object oriented design.

如果你有一个方法/变量,你只需要一个实例(例如一个常量或一个实用程序)方法),然后让它静止。理解虽然使方法静态意味着它不能被覆盖。因此,如果您想要在子类中覆盖一个方法,那么请不要将其设置为静态。

If you have a method/variable that you only need one instance of (e.g. a constant or a utility method), then just make it static. Understand though that making a method static means it cannot be overridden. So if you have a method you want to override in a subclass, then don't make it static.

一般的经验法则是 - 如果您只需要一个副本它,让它静止。如果每个实例需要一个副本,则将其设置为非静态。

The general rule of thumb is - if you need only one copy of it, make it static. If you need a copy per instance, then make it non static.

这篇关于何时使用静态方法和字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆