关于JAVA类的初始化顺序

来源:互联网 发布:淘宝店铺广告语 编辑:程序博客网 时间:2024/05/30 02:24

 JAVA中的初始化由以下几部分组成:属性,方法,static块,非static块,构造方法。以下给出一个测试程序:
public class Test {
 public static void main(String[] args) {
  new Student();
 }
}
class Person {
 static int age = 1;
 public static void f1() {
  System.out.println("Person function()");
 }
 static {
  f1();
  System.out.println("Age = " + age + " Static Person");
 }
 
 public Person() {
  System.out.println("Age = " + age + " Construct Person");
 }
 
 {
  System.out.println("Age = " + age + " Non-Static Person");
 }
}
class Student extends Person {
 static String name = "lisi";
 public static void f2() {
  System.out.println("Student function()");
 }
 static {
  f2();
  System.out.println("Name = " + name + " Age = " + age + " Static Student");
 }
 
 public Student() {
  System.out.println("Name = " + name + " Age = " + age + " Construct Student");
 }
 
 {
  System.out.println("Name = " + name + " Age = " + age + " Non-static Student");
 }


以上代码中,除了主类外,还定义了两个类,Student类继承Person类。每个类中都含有属性,方法,static块,非static块,构造方法。执行后,输出如下:
Person function()
Age = 1 Static Person
Student function()
Name = lisi Age = 1 Static Student
Age = 1 Non-Static Person
Age = 1 Construct Person
Name = lisi Age = 1 Non-static Student
Name = lisi Age = 1 Construct Student

从输出内容可以看出,在某一个类中类总是会先初始化属性和方法,接着是static块, 非static块,构造方法。构造方法是最后才执行的哟!如果该类继承父类,则会先初始化父类的属性和方法,再是static块,然后是自己的属性和方法和static块,然后是父类的非static块和构造方法,最后是自己的非static块和构造方法。这里的非static块可以看成是构造之前的初始化代码块。 
1 0
原创粉丝点击