静态块,代码块,构造方法的区别

来源:互联网 发布:淘宝折扣app哪个好 编辑:程序博客网 时间:2024/05/21 19:22

静态块:static{  }

代码块:{  }

构造块;类 对象 =new 类()

 执行的顺序(优先级:静态块>代码块》构造块)

 代码块:

public  class Test{

public static void main(String args[]) Exception throws{

              new Leaf();
new Leaf("ABC);
new Leaf();

 }

}

//静态初始化块,构造块,构造方法(226-268)
class Root{
static {
System.out.println("Root1的静态初始化");
}
{
System.out.println("Root1的构造块");
}
public Root() {
System.out.println("Root1的构造方法");
}
}
class Mid extends Root{
static {
System.out.println("Mid的静态初始化");
}
{
System.out.println("Mid的构造块");
}
public Mid() {
//super();
System.out.println("Mid的构造方法");
}
}
class Leaf extends Mid{
static {
System.out.println("Leaf的静态初始化");
}
{
System.out.println("Leaf的构造块");
}
public Leaf() {
super();
System.out.println("Leaf的构造方法");
}
public Leaf(String msg) {
this();
System.out.println(msg);
}
}

总结:先加载类,在加载对象,有了类才能加载对象,先执行static静态块,在执行构造块,最后执行构造器·,再次执行时jvm(java虚拟机已经有了此类),不会再执行static静态块,直接执行代码块,构造块

运行结果:

Mid的静态初始化
Leaf的静态初始化
Root1的构造块
Root1的构造方法
Mid的构造块
Mid的构造方法
Leaf的构造块
Leaf的构造方法
Root1的构造块
Root1的构造方法
Mid的构造块
Mid的构造方法
Leaf的构造块
Leaf的构造方法
ABC
Root1的构造块
Root1的构造方法
Mid的构造块
Mid的构造方法
Leaf的构造块
Leaf的构造方法

0 0