首页 > 解决方案 > 为什么不使用静态方法?

问题描述

所以,我对 Java 还是很陌生,据我所知,这两者是相同的:

public class HelloWorld {
    public void test(String test) {
        System.out.println(test);
    }
    public static void main(String args[]) {
        HelloWorld helloworld = new HelloWorld();
        helloworld.test("Hello world!");
    }
}

public class HelloWorld {
    public static void test(String test) {
        System.out.println(test);
    }
    public static void main(String args[]) {
        test("Hello world!");
    }
}

这两者是同一件事吗?您为什么会使用其中一个?

标签: javamethodsstatic

解决方案


静态方法有时很难测试。

非静态方法指定对象的行为。静态方法通常用于实用程序函数(例如Collections.sort()


推荐阅读