码迷,mamicode.com
首页 > 编程语言 > 详细

Java 初始化字段方式和顺序

时间:2015-01-22 21:49:43      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

Java 初始化字段方式和顺序:

  1. 类加载时直接初始化静态字段;

  2. 类加载时调用静态方法初始化静态字段;

  3. 实例化对象时,在调用构造函数之前代码块中初始化字段;

  4. 实例化对象时,在调用构造函数之时初始化字段;

  初始化字段顺序1->2->3->4

 

代码如下:

public class Employee {

//实例化对象时,在调用构造函数之前前初始化字段;

    private int id; // 实例化对象时初始化为0

    private String name; // 实例化对象时初始化为null

    private boolean flag; // 实例化对象时初始化为false



    private static int age = 22; // 加载类时初始化为22



    // 在构造函数之前初始化

    {

        int num = 1111; // 实例化对象时初始化为1111

        String name = "QA";// 实例化对象时初始化为QA

        setId(num); // 实例化对象时调用

        SetName(name); // 实例化对象时调用

        System.out.println("call instance method");

    }



//类加载时调用静态方法初始化静态字段;

    static {

        System.out.println("age is: " + age);

        age = 30; // 加载类时初始化为33

        print(); // 加载类时时调用

    }



    public void SetName(String name) {

        this.name = name;

    }



    public int getId() {

        return id;

    }



    public String getName() {

        return name;

    }



    public static int getAge() {

        return age;

    }



    public void setId(int num) {

        id = num;

    }



    public static void print() {

        System.out.println("call static method");

    }



    public Employee() {

        // TODO Auto-generated constructor stub

    }



    public Employee(int id, String name) {

        // TODO Auto-generated constructor stub

        this.id = id;

        this.name = name;

        System.out.println("call constructor method");

    }



    public static void main(String[] args) {

        // TODO Auto-generated method stub

        System.out.println("---------------------------");



        System.out.println("age is: " + Employee.getAge());

        System.out.println("---------------------------");



        Employee e = new Employee();

        System.out.println("id is: " + e.getId());

        System.out.println("name is: " + e.getName());

        System.out.println("---------------------------");



        Employee e2 = new Employee(2222, "Dev");

        System.out.println("id is: " + e2.getId());

        System.out.println("name is: " + e2.getName());

    }

}

运行结果:

age is: 22

call static method

---------------------------

age is: 30

---------------------------

call instance method

id is: 1111

name is: QA

---------------------------

call instance method

call constructor method

id is: 2222

name is: Dev

Java 初始化字段方式和顺序

标签:

原文地址:http://www.cnblogs.com/csu_xajy/p/4242654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!