除了易于调用之外,java中还可以使用静态方法/函数吗? [英] Is there any use of static methods/functions in java other than ease of calling?

查看:99
本文介绍了除了易于调用之外,java中还可以使用静态方法/函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将方法声明为静态方法是否具有其他优点,除了可以在不实例化类的情况下调用该方法之外?

解决方案

不需要实例化类来调用方法本身就是一个优点.考虑方法库,例如java.lang.Math.

静态方法也用作工厂方法-您调用静态方法以获取对象-通常是某些接口的实现.想法是,该方法可以根据传递的参数找出要为您构建的特定实现.如果必须先有一个对象实例,然后才能调用这种方法,则要么拥有一个鸡和蛋,要么要创建第二个类的实例,而只是调用工厂方法来为您提供第一个类的实例. /p>

您可能还会发现有关方法是否应为静态的StackOverflow问题默认情况下,尤其是已接受的答案.

Does declaring a method as static have any advantage except that it can be called without instantiating a class?

解决方案

Not needing to instantiate a class to call a method can be an advantage in itself. Consider libraries of methods, such as java.lang.Math.

Static methods are also used as factory methods -- you call a static method to get an object -- usually an implementation of some interface. The idea is that the method can figure out which specific implementation to build for you given the parameters you pass it. If you had to have an object instance before you could call such a method you'd either have a chicken-and-egg or would be creating instances of a second class just to call a factory method to give you instances of the first.

You might also find this StackOverflow question on whether or not methods should be static by default of interest, especially the accepted answer.

这篇关于除了易于调用之外,java中还可以使用静态方法/函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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