学习目标:初步了解static的用法
- 初步了解static的错与对
学习内容:
- 类初始化加载顺序
- 对象调用静态/非静态变量及方法
- 类调用静态/非静态变量及方法
学习时间:
20分钟
学习产出:
1.类初始化加载顺序
public class Student {
{
System.out.println("匿名代码块");
}
static {
System.out.println("静态代码块");
}
public Student() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Student student1 = new Student();
System.out.println("====================");
Student student2 = new Student();
}
}
2.对象可正常调用类中的静态和非静态变量及方法
public class Student {
private static int age;
private double score;
public static void sleep(){
System.out.println("上课睡觉");
}
public void study() {
System.out.println("上课听讲");
}
public static void main(String[] args) {
Student student1 = new Student();
student1.study();
student1.sleep();
System.out.println(student1.age);
System.out.println(student1.score);
}
}
3.类无法直接调用非静态变量及方法