您的位置:首页 > 编程语言 > Java开发

Think in java 答案_Chapter 4_Exercise 4

2007-01-22 14:09 525 查看
阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx

/****************** Exercise 4 ******************
* Complete Exercise 3 by creating objects to
* attach to the array of references.
***********************************************/
public class E04_ObjectArray {
E02_OverloadedConstructor[] array =
new E02_OverloadedConstructor[5];
public E04_ObjectArray() {
for(int i = 0; i < array.length; i++)
array[i] = new E02_OverloadedConstructor();
}
// An overloaded constructor that calls the
// overloaded constructor from Exercise 2:
public E04_ObjectArray(String s) {
for(int i = 0; i < array.length; i++)
array[i] = new E02_OverloadedConstructor(s);
}
public static void main(String args[]) {
new E04_ObjectArray();
new E04_ObjectArray("Overloaded");
}
}

//+M java E04_ObjectArray

**Since the array is defined as a field of the class, it must be initialized in the constructor (if you try to initialize it inside main( ) you’ll get a complaint that a non-static field cannot be accessed inside a static method). I’ve gone the extra step here and created a second, overloaded constructor that initializes the array by calling the overloaded constructor from Exercise 2. The output is:

Default constructor
Default constructor
Default constructor
Default constructor
Default constructor
Default constructor
Overloaded
Default constructor
Overloaded
Default constructor
Overloaded
Default constructor
Overloaded
Default constructor
Overloaded
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: