是否可以在构造类的单个实例之前调用静态方法?
发布于 2009-08-29 18:17:45
当然,这是静态方法的目的:
class ClassName {
public static void staticMethod() {
}
}为了调用静态方法,您必须导入类:
import ClassName;
// ...
ClassName.staticMethod();或者使用静态导入(Java 5或更高版本):
import static ClassName.staticMethod;
// ...
staticMethod();发布于 2009-08-29 18:17:50
是的,这正是静态方法的作用所在。
ClassName.staticMethodName();发布于 2009-08-29 18:35:38
正如其他人已经建议的那样,在不(之前)创建实例的情况下调用类上的静态方法绝对是可能的--这就是单例的工作方式。例如:
import java.util.Calendar;
public class MyClass
{
// the static method Calendar.getInstance() is used to create
// [Calendar]s--note that [Calendar]'s constructor is private
private Calendar now = Calendar.getInstance();
}如果您的意思是“是否可以在初始化第一个对象之前自动调用特定的静态方法?”,请参见下面的内容:
public class MyClass
{
// the static block is garanteed to be executed before the
// first [MyClass] object is created.
static {
MyClass.init();
}
private static void init() {
// do something ...
}
}https://stackoverflow.com/questions/1352028
复制相似问题