static关键字详解
与类一起运行
只执行一次
public class Person {
//2: 赋初始值
{
System.out.println("匿名代码块");
}
//1: 只执行一次
static{
System.out.println("静态代码块");
}
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person = new Person();
System.out.println("==============");
Person person1 = new Person();
}
}
静态导入包
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);
}
}
静态与非静态的区别
public class Student {
private static int age;//静态变量
private double score; //非静态变量
//非静态方法
public void run(){
}
//静态方法
public static void go(){
}
public static void main(String[] args) {
Student.go();
go();
new Student().run();
}
}