我下面举的例子是在Thinking in Java中摘取的,讲的比较透彻,这里与大家一起分享。
package com.thinking.chapter4; class Bowl { public Bowl(int i) { System.out.println(i + " from Bowl"); } void f1(int marker) { System.out.println("f1( " + marker + " )"); } } class Table { static Bowl bowl1 = new Bowl(1); public Table() { System.out.println(" from table"); bowl2.f1(1); } void f2(int marker) { System.out.println("f2( " + marker + " )"); } static Bowl bowl2 = new Bowl(2); } class Cupboard { Bowl bowl3 = new Bowl(3); static Bowl bowl4 = new Bowl(4); public Cupboard() { System.out.println("Cupboard()"); bowl4.f1(2); } void f3(int marker) { System.out.println("f3( " + marker + " )"); } static Bowl bowl5 = new Bowl(5); } public class Init { static Table table = new Table(); static Cupboard cupboard = new Cupboard(); public static void main(String[] args) { System.out.println("create1 new Cupboard in main"); new Cupboard(); System.out.println("create2 new Cupboard in main"); new Cupboard(); table.f2(1); cupboard.f3(1); } }这是其输出的结果。
1 from Bowl 2 from Bowl from table f1( 1 ) 4 from Bowl 5 from Bowl 3 from Bowl Cupboard() f1( 2 ) create1 new Cupboard in main 3 from Bowl Cupboard() f1( 2 ) create2 new Cupboard in main 3 from Bowl Cupboard() f1( 2 ) f2( 1 ) f3( 1 )总结:
1.一个类成员中的属性,分为static的和non-static的,对static的属性该类的所有对象共有一份,non-static的属性每个对象有一份。
2.如果在声明类属性时直接初始化,那么这个初始化是先于构造函数执行的,其实还有一份默认初始化。
这一点比较容易让大家忽略。举个栗子:
class Student { int age = 18; Student() { age = 19; } }对于这个Student类,如果我们在一个main方法中new了一个Student类的对象,那么age属性的初始化过程时这样的:
(1)首先,由于age是int类型,所以age被默认初始化为0
(2)然后,由于我们有显式赋于值18,所以age的值又变为了18
(3)最后,由于我们的构造函数中又对age进行了初始化,所以最后age变为了19
我这里举的是例子中属性类型是int,对于其他类型一样适用,Object对象默认初始化为null。
3.在创建某对象时,如果该对象中既有static属性又有non-static属性,而且他们都在声明时被初始化,那么程序将先初始化static属性,然后初始化non-static属性。