我想知道什么时候使用静态方法?假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
例子:
Obj x = new Obj();
x.someMethod();
或:
Obj.someMethod(); // Is this the static way?
我很困惑!
我想知道什么时候使用静态方法?假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
例子:
Obj x = new Obj();
x.someMethod();
或:
Obj.someMethod(); // Is this the static way?
我很困惑!
当前回答
使用静态方法的唯一合理的地方可能是Math函数,当然main()必须是静态的,也可能是小型工厂方法。但是逻辑不应该保存在静态方法中。
其他回答
不,静态方法不与实例关联;他们属于这个阶层。静态方法是第二个例子;实例方法是第一个。
我发现了一个很好的描述,当使用静态方法:
没有硬性的、写得很好的规则来决定什么时候使一个方法静态或非静态,但是有一些基于经验的观察,这不仅有助于使一个方法静态,而且还教会了什么时候在Java中使用静态方法。你应该考虑在Java中让一个方法是静态的:
If a method doesn't modify state of object, or not using any instance variables. You want to call method without creating instance of that class. A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument. Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not. If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.
来源在这里
我想知道什么时候使用静态方法?
静态方法的一个常见用途是访问静态字段。 但是你可以有静态方法,而不需要引用静态变量。不引用静态变量的Helper方法可以在一些java类中找到,如java.lang. math 公共静态int min(int a, int b) { 返回(a <= b) ?A: b; } 另一个用例,我认为这些方法与同步方法相结合是在多线程环境中实现类级锁定。
假设我有一个类,有几个getter和setter,一个或两个方法,我希望这些方法只能在类的实例对象上调用。这是否意味着我应该使用静态方法?
如果你需要访问类的实例对象上的方法,你的方法应该是非静态的。
Oracle文档页提供了更多详细信息。
不是所有的实例和类变量和方法的组合都被允许:
实例方法可以直接访问实例变量和实例方法。 实例方法可以直接访问类变量和类方法。 类方法可以直接访问类变量和类方法。 类方法不能直接访问实例变量或实例方法——它们必须使用对象引用。而且,类方法不能使用this关键字,因为没有this的实例可以引用。
在阅读了Misko的文章之后,我相信静态方法从测试的角度来看是不好的。相反,您应该使用工厂(可能使用像Guice这样的依赖注入工具)。
我如何确保我只有一个东西
只吃一种 问题是"我如何确保我 只吃一种东西”是很好的 回避了。实例化一个 单个ApplicationFactory在你的 主要的,结果,只有你 实例化所有的单个实例 你的独生子女。
静态方法的基本问题是它们是过程代码
静态方法的基本问题是 它们是过程代码。我没有 知道如何对过程代码进行单元测试。 单元测试假设我可以 实例化我的应用程序的一部分 在隔离。在实例化过程中 我将依赖项与 mock /友军替换 真正的依赖关系。与程序 编程没有什么可以“连接”的 由于没有对象,代码 数据是分开的。
当您不想在代码中创建对象来调用方法时,只需将该方法声明为静态方法。因为静态方法不需要调用实例,但这里的问题是,并不是所有的静态方法都由JVM自动调用。此特权仅由main()节点享有。“public static void main[字符串…]方法,因为在运行时,这是方法Signature public“static”void main[], JVM寻求作为开始执行代码的入口点。
例子:
public class Demo
{
public static void main(String... args)
{
Demo d = new Demo();
System.out.println("This static method is executed by JVM");
//Now to call the static method Displ() you can use the below methods:
Displ(); //By method name itself
Demo.Displ(); //By using class name//Recommended
d.Displ(); //By using instance //Not recommended
}
public static void Displ()
{
System.out.println("This static method needs to be called explicitly");
}
}
输出: 这个静态方法由JVM执行 这个静态方法需要显式调用 这个静态方法需要显式调用 这个静态方法需要显式调用