1. static修饰类成员变量
static修饰的类成员变量称为静态变量,其属于类,不属于对象,即可直接通过类的方式调用静态成员变量。
public class Student {
private static int age; // 静态变量。可通过类直接调用它。
private double score; // 非静态变量。只能通过对象才能调用它。public static void main(String[] args) { System.out.println(Student.age); Student s = new Student(); System.out.println(s.age); System.out.println(s.score); }
}
2.static修饰类成员函数
public class Student {
public void run() {} // 非静态成员函数
public static void go() {} // 静态成员函数
public static void main(String[] args) {
// 可直接通过类,调用类中的静态成员函数
Student.go();
// 非静态成员函数只能通过对象调用
// 静态成员函数也可通过对象调用
Student student = new Student();
student.run();
student.go();
}
}
3.static静态代码块
系统先执行静态代码块,再执行匿名代码块,再执行构造函数
public class Student {
// 系统先执行静态代码块,再执行匿名代码块,再执行构造函数
{
// 匿名代码块:用来赋初始值
// 每次执行构造函数前,都会先执行匿名代码块
}
// static代码块
static {
// 静态代码块只会在类被加载时被执行一次,用来初始化静态变量
// 如第一次new Student时会执行静态代码块,第二次new Student时就不会再执行静态代码块
}
}
4. static静态导入包
静态导入包类似于C++中的using namespace语句
// 静态导入包
import static java.lang.Math.PI;
import static java.lang.Math.random;
public class Student {
public static void main(String[] args) {
// System.out.println(Math.random());
// 使用静态导入包后,此处可直接写random()
System.out.println(random());
System.out.println(PI);
}
}