Java:何时使用静态方法 [英] Java: when to use static methods

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

问题描述

我想知道何时使用静态方法?假如我有一个带有一些getter和setter的类,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?



例如

  Obj x = new Obj(); 
x.someMethod

  Obj.someMethod 

(这是静态方式吗? )



我很困惑!

解决方案

一条规则 - 拇指:问问自己即使没有构建Obj,这个方法也有意义吗?如果是这样,那肯定是静态的。



所以在类 Car 中你可能有一个方法 double convertMpgToKpl(double mpg)这将是静态的,因为人们可能想知道35mpg转换为什么,即使没有人建造过汽车。但是 void setMileage(double mpg)(设置一个特定Car的效率)不能是静态的,因为在构造任何Car之前调用该方法是不可思议的。 / p>

(顺便说一句,反之并非总是如此:你有时可能会有一个涉及两个 Car 对象的方法,并且仍然希望它是静态的。例如 Car theMoreEfficientOf(Car c1,Car c2)。虽然这可以转换为非静态版本,但有些人会认为,因为那里不是特权选择哪个Car更重要,你不应该强迫调用者选择一个Car作为你将调用方法的对象。这种情况只占所有静态方法的一小部分,虽然。)


I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?

e.g

Obj x = new Obj();
x.someMethod

or

Obj.someMethod

(is this the static way?)

I'm rather confused!

解决方案

One rule-of-thumb: ask yourself "does it make sense to call this method, even if no Obj has been constructed yet?" If so, it should definitely be static.

So in a class Car you might have a method double convertMpgToKpl(double mpg) which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But void setMileage(double mpg) (which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.

(Btw, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g. Car theMoreEfficientOf( Car c1, Car c2 ). Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.)

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

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