首先我自訂了一個Friend 類別,用來紀錄Friend 們的資料。
package demo;
/**
* custom object Friend
*
* @author boywhy
*/
public class Friend {
public String Name;
public String Tel;
public String birt;
}
接下來是主程式
package demo;
/**
* Demo Main
*
* @author boywhy
*/
public class Demo {
public static void main(String[] args) {
try {
Friend[] mFriends = new Friend[3];
mFriends[0].Name = "張大富";
} catch (Exception e) {
e.printStackTrace();
}
}
}
發生了以下錯誤
第13行是在設定姓名的部份
Java allocates N places to put your objects in. It does NOT instantiate your objects for you.
Java只是幫你配置了N個空間的記憶體位置給你放自訂物件,並沒有幫你自動初始化物件。
我們只須要在使用自訂物件前把它初始化,便可以解決上述問題。
for (int i = 0; i < mFriends.length; i++) {
mFriends[i]=new Friend();
}
完整主程式如下:
package demo;
/**
* Demo Main
*
* @author boywhy
*/
public class Demo {
public static void main(String[] args) {
try {
Friend[] mFriends = new Friend[3];
//Init Custom Object
for (int i = 0; i < mFriends.length; i++) {
mFriends[i]=new Friend();
}
mFriends[0].Name = "張大富";
} catch (Exception e) {
e.printStackTrace();
}
}
}
參考資料
http://stackoverflow.com/questions/20402764/creating-array-of-custom-objects-in-java


沒有留言:
張貼留言