什么时候不要在 Java 中使用 static 关键字? [英] When NOT to use the static keyword in Java?

查看:24
本文介绍了什么时候不要在 Java 中使用 static 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中在方法签名上使用 static 关键字何时被认为是不好的做法?如果一个方法基于一些参数执行一个函数,并且不需要访问非静态字段,那么你不是总是希望这些类型的方法是静态的吗?

When is it considered poor practice to use the static keyword in Java on method signatures? If a method performs a function based upon some arguments, and does not require access to fields that are not static, then wouldn't you always want these types of methods to be static?

推荐答案

可能不希望它是静态的一个原因是允许它在子类中被覆盖.换句话说,行为可能不取决于对象内的数据,而是取决于对象的确切类型.例如,您可能有一个通用的集合类型,带有一个 isReadOnly 属性,该属性在始终可变的集合中返回 false,在始终可变的集合中返回 true不可变集合,并依赖于其他实例变量.

One reason why you may not want it to be static is to allow it to be overridden in a subclass. In other words, the behaviour may not depend on the data within the object, but on the exact type of the object. For example, you might have a general collection type, with an isReadOnly property which would return false in always-mutable collections, true in always-immutable collections, and depend on instance variables in others.

但是,根据我的经验,这种情况很少见 - 通常应该明确指定以保持清晰.通常我会创建一个不依赖于任何静态对象状态的方法.

However, this is quite rare in my experience - and should usually be explicitly specified for clarity. Normally I'd make a method which doesn't depend on any object state static.

这篇关于什么时候不要在 Java 中使用 static 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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