一、静态成员
static可以修饰成员变量,成员方法,不能修饰局部变量
static可以修饰成员内部类,不能修饰局部内部类、普通类
静态成员在类加载到内存时就已确定,局部变量随着方法进栈而存在
- 变量被对象共享,就用static修饰
- 方法不访问对象的特有数据,就用static修饰
// 学生类
public class Student {
private String name; // 姓名
private int age; // 年龄
private int id; // 学号
private static int idCounter; // 学号基数
private static String room; // 所在教室
static {
idCounter = 1000;
room = "工大204室";
}
public Student(String name, int age) {
this.name = name;
this.age = age;
this.id = ++idCounter; // 【学号自增】
}
/**
* 展示学生信息
*/
void showStudentMessage() {
System.out.println("姓名:" + name + ",年龄:" + age +
",学号:" + id + ",教室:" + room);
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Student stu1 = new Student("鱼悠奕", 21);
stu1.showStudentMessage();
Student stu2 = new Student("啦啦啦", 26);
stu2.showStudentMessage();
}
}
二、静态代码块
典型用途:一次性对静态成员变量进行赋值
首次使用类时,静态代码块执行唯一的一次
静态内容先于非静态内容,静态代码块在构造方法之前执行
// 中国人
public class Chinese {
static String country; // 国家
static String language; // 语言
static {
country = "中国";
language = "中文";
System.out.println("static block...");
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Chinese one = new Chinese();
Chinese two = new Chinese();
}
}