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

问题描述

我想知道人们如何决定是否将一个方法定义为静态方法.我知道一种方法只能在不需要访问实例字段的情况下才能定义为静态方法.因此,假设我们有一个不访问实例字段的方法,您是否总是将这种方法定义为静态方法,还是仅在需要静态调用它(不引用实例)的情况下?

I'd like to know how people decide whether to define a method as static. I'm aware that a method can only be defined as static if it doesn't require access to instance fields. So let's say we have a method that does not access instance fields, do you always define such a method as static, or only if you need to call it statically (without a reference to an instance).

也许问相同问题的另一种方法是默认使用静态还是非静态?

Perhaps another way of asking the same question is whether you use static or non-static as the default?

推荐答案

我会尽可能使用静态方法.优点:

I use static methods whenever I can. Advantages:

  • 从实例方法内部调用静态方法时,可以确保当前对象的状态没有副作用.
  • 从静态方法内部,可以确保不会意外修改对象实例的任何状态.
  • 您可以从类外部使用静态方法,而无需构造实例.如果可以将方法设为静态,则显然不需要实例,因此不需要实例.
  • 静态方法的效率可能会更高,因为不需要传递"this"指针,并且不需要动态分配.

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

07-22 21:30
查看更多