1.静态(static)成员变量和静态代码块代码块
static修饰的成员都是类成员,会随着JVM加载类的时候加载而执行,而没有被static修饰的成员也被称为实例成员,需要创建对象才会随之加载到堆内存。所以静态的会优先非静态的。静态成员变量优先于静态代码块执行;
2.非静态代码块和非静态成员变量
非静态代码块和静态代码块都是在JVM加载类时且在构造方法执行之前执行,非静态代码块在类中都可以定义多个;非静态代码块是在类被实例化的时候执行。每被实例化一次,就会被执行一次;非静态成员变量优先于非静态代码块和构造方法执行;
3.构造方法
执行构造方法的时候,在执行方法体之前存在隐式三步:
1)构造方法体的第一行是this语句,则不会执行隐式三步,
2)构造方法体的第一行是super语句,则调用相应的父类的构造方法,
3)构造方法体的第一行既不是this语句也不是super语句,则隐式调用super(),即其父类的默认构造方法,这也是为什么一个父类通常要提供默认构造方法的原因;
代码示例:
package com.dhcc.demo.springbootymldemo02.test;
public class Teacher {
private String name;
private Integer age;
public Teacher(String str) {
System.out.println(str + "--成员变量Teacher初始化");
}
}
package com.dhcc.demo.springbootymldemo02.test;
import java.sql.Timestamp;
public class Person {
private static Teacher teacher = new Teacher("静态");
private Teacher teacherOne = new Teacher("非静态");
private Integer no;
private Integer age;
private String name;
static {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try {
Thread.sleep(1000);
System.out.println("------父类的静态代码块执行------" + timestamp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
{
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try {
Thread.sleep(1000);
System.out.println("------父类的非静态代码块执行------" + timestamp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Person() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try {
Thread.sleep(1000);
System.out.println("------父类的构造方法执行------" + timestamp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.dhcc.demo.springbootymldemo02.test;
import java.sql.Timestamp;
public class Student extends Person {
private Integer sNo;
private Integer classNO;
static {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try {
Thread.sleep(1000);
System.out.println("------Student类的静态代码块执行------" + timestamp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
{
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try {
Thread.sleep(1000);
System.out.println("------Student类的非静态代码块执行------" + timestamp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Student() {
super();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try {
Thread.sleep(1000);
System.out.println("------Student类的构造方法执行------" + timestamp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.dhcc.demo.springbootymldemo02.test;
public class Test {
public static void main(String[] args) {
new Student();
}
}
静态--成员变量Teacher初始化
------父类的静态代码块执行------2022-03-28 11:16:40.657
------Student类的静态代码块执行------2022-03-28 11:16:41.661
非静态--成员变量Teacher初始化
------父类的非静态代码块执行------2022-03-28 11:16:42.669
------父类的构造方法执行------2022-03-28 11:16:43.679
------Student类的非静态代码块执行------2022-03-28 11:16:44.682
------Student类的构造方法执行------2022-03-28 11:16:45.689