- 静态变量使用类名可以直接调用
public class Student {
private static int age; //静态变量 一般用于多线程
private double score; //非静态变量
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age);
//System.out.println(Student.score); 报错
System.out.println(s1.age);
System.out.println(s1.score);
}
}
- 非静态方法需要先new一个对象才能调用,静态方法可以直接调用
public class Student {
public void run(){
go(); //非静态方法可以直接调用静态方法
}
public static void go(){
}
public static void main(String[] args) {
new Student().run(); //非静态方法需要先new一个对象才能调用
go(); //静态方法直接调用
}
}
- 静态代码块
public class Person {
//第三个执行
public Person() {
System.out.println("构造方法");
}
//第二个执行,赋初始值
{
//匿名代码块,创建对象时才执行
System.out.println("匿名代码块");
}
//第一个执行,只执行一次
static {
//静态代码块,初始化一些东西,类加载就执行
System.out.println("静态代码块");
}
public static void main(String[] args) {
Person person1 = new Person();
System.out.println("==========");
Person person2 = new Person();
}
}
执行顺序:静态代码块=>匿名代码块=>构造方法
重复创建对象时,静态代码块不会再次执行(只执行一次)
- 静态导入包
//输出随机数
public class Test {
public static void main(String[] args) {
System.out.println(Math.random());
}
}
//or
//静态导入包
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);
}
}