这一章节我们接着上一章节的内容。
(3)静态数据的初始化
a.静态数据只会执行一次
package com.ray.testobject; public class Test { private static Book book1 = new Book(1); private static Book book2 = new Book(2); public Test() { System.out.println("create test"); book1.say(); book2.say(); Book book3 = new Book(3); book3.say(); } public static void main(String[] args) { new Test(); new Test(); } } class Book { private int id; public Book(int id) { this.id = id; System.out.println("create book:" + id); } public void say() { System.out.println("hi, my name is book-" + id); } }
输出:
create book:1
create book:2
create test
hi, my name is book-1
hi, my name is book-2
create book:3
hi, my name is book-3
create test
hi, my name is book-1
hi, my name is book-2
create book:3
hi, my name is book-3
从结果可以看见,book1和book2只在第一次创建Test的时候创建了一次,然后再次创建Test时就不再创建book1和book2。
b.如果不被引用或者不new,对象里面的静态属性域不会创建。
我们修改一下上面的代码:
package com.ray.testobject; public class Test { public Test() { } public static void main(String[] args) { } } class Book { private int id; public Book(int id) { this.id = id; System.out.println("create book:" + id); } public void say() { System.out.println("hi, my name is book-" + id); } } class GroupOfBooks { private static Book book; public static Book getBook() { book = new Book(99); return book; } }
上面的代码是不会执行new Book(99)这一行的。
我们再进行修改,给出两种执行new Book(99)的例子:
package com.ray.testobject; public class Test { public Test() { } public static void main(String[] args) { new GroupOfBooks(); } } class Book { private int id; public Book(int id) { this.id = id; System.out.println("create book:" + id); } public void say() { System.out.println("hi, my name is book-" + id); } } class GroupOfBooks { private static Book book; public static Book getBook() { book = new Book(99); return book; } }
package com.ray.testobject; public class Test { public Test() { } public static void main(String[] args) { GroupOfBooks.getBook(); } } class Book { private int id; public Book(int id) { this.id = id; System.out.println("create book:" + id); } public void say() { System.out.println("hi, my name is book-" + id); } } class GroupOfBooks { private static Book book; public static Book getBook() { book = new Book(99); return book; } }
上面两段代码同样输出:
create book:99
这里总结一下对象创建的过程:
1.查询.class文件的路径
2.载入.class文件,执行对象的静态方法或者静态属性域
3.new对象,然后分配内存空间(内存空间清零,则对象回收,引用变成null)
4.执行属性域初始化
5.执行构造器
总结:这一章节主要讨论了静态属性域的初始化。
这一章节就到这里,谢谢。
-----------------------------------
版权声明:本文为博主原创文章,未经博主允许不得转载。