//static
public class Student{
private static int age;//静态的变量 多线程!
private double score;//非静态的变量
public void run(){
go();
}
public static void go(){
}
public static void main(String[] args) {
Student.go();
}
}
通过以上代码可以看出,非静态的方法可以直接调用静态的方法。但是静态的方法无法调用非静态的方法。(可以理解成静态的方法是先于非静态方法和类一起加载进来的,因此无法用“先来的指挥后来的”)在主方法中,可以通过Student.go();来直接调用静态方法。通过new Student().run();来调用非静态的方法,当然这样也可以调用静态的方法。
public final class Person {
//2:赋初值
{
System.out.println("匿名代码块");
}
//1:只执行一次
static {
System.out.println("静态代码块");
}
//3
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person1 = new Person();
System.out.println("========================");
Person person2 = new Person();
}
}
运行结果如下:
可以看出static方法块只有在第一次执行时被调用,以后都不会被执行。
注意:这个类中用了final关键字,使得这个类无法被继承。
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(random());
System.out.println(PI);
}
}
这里用static静态导入包,在方法中就可以不用具体注明各个包的完整路径,直接调用即可。