在Java中,类的静态方法有什么缺点吗? [英] In Java, is there any disadvantage to static methods on a class?

查看:195
本文介绍了在Java中,类的静态方法有什么缺点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设在我的编码环境中强加了一条规则(或者经验法则),即任何不使用,修改或以其他方式需要任何实例变量来完成其工作的类的方法,静止的。这样做是否存在固有的编译时间,运行时间或任何其他缺点?

Lets assume that a rule (or rule of thumb, anyway), has been imposed in my coding environment that any method on a class that doesn't use, modify, or otherwise need any instance variables to do its work, be made static. Is there any inherent compile time, runtime, or any other disadvantage to doing this?

(编辑以供进一步说明)

(edited for further clarifications)

我知道这个问题有点开放和模糊,所以我为此道歉。我的提问意图主要是辅助方法。实用程序类(具有私有CTOR,因此无法实例化)作为我们已经执行的静态方法的持有者。我在这里的问题更多的是帮助主类API的这些小方法。

I know the question was somewhat open ended and vague so I apologize for that. My intent in asking was in the context of mostly "helper" methods. Utility classes (with private CTORs so they can't be instantiated) as holders for static methods we already do. My question here was more in line of these little methods that HELP OUT the main class API.

我可能在一个类上有4或5个主API /实例方法真正的工作,但在这样做的过程中,他们共享一些共同的功能,可能只是在处理API方法的输入参数,而不是内部状态。这些是我通常在他们自己的帮助方法中提取的代码部分,如果他们不需要访问类的状态,请将它们设置为静态。

I might have 4 or 5 main API/instance methods on a class that do the real work, but in the course of doing so they share some common functionality that might only be working on the input parameters to the API method, and not internal state. THESE are the code sections I typically pull out into their own helper methods, and if they don't need to access the class' state, make them static.

我的问题因此,这本质上是一个坏主意,如果是这样,为什么? (或者为什么不呢?)

My question was thus, is this inherently a bad idea, and if so, why? (Or why not?)

推荐答案

主要的缺点是你不能在运行时交换,覆盖或选择方法实现。

The main disadvantage is that you cannot swap, override or choose method implementations at runtime.

这篇关于在Java中,类的静态方法有什么缺点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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