通常情况下想使用Java类里定义的变量和方法,必须先New一个对象,然后通过这个对象访问变量和方法。但是如果将Java类中的变量和方法(method)声明成static,就可以直接通过类名访问,不要New一个对象,因此static变量和方法又叫‘类变量’和‘类方法'。
Java的main函数必须声明成static的,因为JVM在runmain函数前没有对象生成,只能通过类方法调用main。
2. Static 变量,方法
Java的main函数必须声明成static的,因为JVM在runmain函数前没有对象生成,只能通过类方法调用main。
1. 非static变量,方法
Class NonStatic {
int nonStaticPar = 1;
void nonStaticMethod() {
System.out.println("Non Static")
}
public static void main(String args[]) {
NonStatic myClass = New NonStatic(); //need to new an object
System.out.println(myClass.nonStaticPar);
myClass.nonStaticMethod();
}
}
2. Static 变量,方法
Class StaticClass {
static int staticPar = 1;
static void nonStaticMethod() {
System.out.println("Non Static")
}
public static void main(String args[]) {
//no need to new an object, we can access the variable and methodthrough the class
System.out.println(StaticClass.nonStaticPar);
StaticClass.nonStaticMethod();
}
}