Create a parent class and test execution order:
public class father {
private String name;
father(){
System.out.println("--父类的无参构造函数--");
}
father(String name){
this.name=name;
System.out.println("--父类的有参构造函数--"+this.name);
}
static{
System.out.println("--父类的静态代码块--");
}
{
System.out.println("--父类的非静态代码块--");
}
public void speak(){
System.out.println("--父类的方法--");
}
public static void main(String[] args) {
System.out.println("--父类主程序--");
father father=new father("父亲的名字");
father.speak();
}
}
Operation results:
–Static code block of the
parent class – –Main program of the parent class
– –Non-static code block of the
parent class – –Parented constructor of the parent class – Father’s name
– Method of the parent class –
Create a subclass to inherit the test execution order of the parent class:
public class Son extends father{
private String name;
static{
System.out.println("--子类的静态代码块--");
}
{
System.out.println("--子类的非静态代码块--");
}
Son(){
System.out.println("--子类的无参构造函数--");
}
Son(String name){
this.name=name;
System.out.println("--子类的有参构造函数--"+this.name);
}
@Override
public void speak(){
System.out.println("--子类Override了父类的方法--");
}
public static void main(String[] args) {
System.out.println("--子类主程序--");
Son son=new Son("儿子的名字");
son.speak();
}
}
Operation results:
–Static code block of the parent class
– –Static code block of the
subclass – –Main program of the subclass
– –Non-static code block of the
parent class – –Parent-free constructor
– –Non-static code of the subclass Block--
Subclass's parameterized constructor-Son's name
-Subclass overrides the parent class's method-
to sum up:
Create a class object, the execution order of each part of the class:
静态代码块—非静态代码块—构造函数—一般方法。
The execution sequence of each part of the subclass inherited from the parent class is:
父静态代码块-子静态代码块-父非静态代码-父无参构造函数-子非静态代码块-子构造函数-方法。
note:
创建子类对象调用子类的构造方法的时候会先调用父类的构造方法,
在子类的构造方法中调用父类的构造方法是用super(),如果没有写super(),
则默认调用父类的无参构造方法。
Source of this article: https://www.cnblogs.com/hxl77/p/8981789.html