public class _422blog {
{
System.out.println("父类的初始化块!");
}
public static void main(String[] args){
new _422_blog();
new _422_blog();
}
}
class _422_blog{
{
System.out.println("子类的初始化块!");
}
}
public class _422blog {
static {
System.out.println("父类的静态初始化块!");
}
public static void main(String[] args){
new _422_blog();
new _422_blog();
}
}
class _422_blog{
static {
System.out.println("子类的静态初始化块!");
}
}
输出结果:
父类的静态初始化块!
子类的静态初始化块!
总结代码
以下代码为更好的理解初始化块
package JavaNotes;
class Root{
static {
System.out.println("Root的静态的初始化块");
}
{
System.out.println("Root的普通初始化块");
}
public Root(){
System.out.println("Root的无参数构造方法");
}
}
class Mid extends Root{
static {
System.out.println("Mid的静态的初始化块");
}
{
System.out.println("Mid的普通初始化块");
}
public Mid(){
System.out.println("Mid的无参数构造方法");
}
public Mid(String msg){
//通过this调用同一类中重载的构造方法
this();
System.out.println("Mid的带参数的构造方法,其值是:" + msg);
}
}
class Leaf extends Mid{
static {
System.out.println("Leaf的静态的初始化块");
}
{
System.out.println("Leaf的普通初始化块");
}
public Leaf(){
//通过super调用父类中有一个字符串参数的构造方法
super("董梦宇");
System.out.println("执行Leaf的构造方法");
}
}
public class _422Test {
public static void main(String[] agrs){
new Leaf();
new Leaf();
}
}