構造函數的一些用法
We may wish to instantiate additional objects related to the Student object:
初始化與對象相關的一些額外對象:
public class Student() {
// Every Student maintains a handle on his/her own individual Transcript object.
private Transcript transcript;
public Student() {
// Create a new Transcript object for this new Student.
transcript = new Transcript();
// etc.
}
}
讀取數據庫來初始化對象屬性:
public class Student {
// Attributes.
String studentId;
String name;
double gpa;
// etc.
// Constructor.
public Student(String id) {
studentId = id;
// Pseudocode.
use studentId as a primary key to retrieve data from the Student table of a
relational database;
if (studentId found in Student table) {
retrieve all data in the Student record;
name = name retrieved from database;
gpa = value retrieved from database;
// etc.
}
}
// etc.
}
和其他已存在的對象交流:
public class Student {
// Details omitted.
// Constructor.
public Student(String major) {
// Alert the student's designated major department that a new student has
// joined the university.
// Pseudocode.
majorDept.notify(about this student ...);
// etc.
}
// etc.
}
好習慣:如果需要有參數的構造函數,最好同時顯示聲明一個無參構造函數。
容易出現的bug:如果給構造函數加上void編譯會通過!不過會被當作方法而不是構造函數!
當有多個構造函數,而且都有共同的初始化內容時,就會出現很多重復的代碼,比如構造一個新學生,我們會做:
1 通知登記辦公室學生的存在
2 給學生創建學生成績報告單
重復引起以后修改必須修改多處,如果使用this 會得到改善
public class Student {
// Attribute details omitted.
// Constructor #1.
public Student() {
// Assign default values to selected attributes ... details omitted.
// Do the things common to all three constructors in this first
// constructor ...
// Pseudocode.
alert the registrar's office of this student's existence
// Create a transcript for this student.
transcript = new Transcript();
}
// Constructor #2.
public Student(String s) {
// ... then, REUSE the code of the first constructor within the second!
this();
// Then, do whatever else extra is necessary for constructor #2.
this.setSsn(s);
}
// Constructor #3.
public Student(String s, String n, int i) {
// ... and REUSE the code of the first constructor within the third!
this();
// Then, do whatever else extra is necessary for constructor #3.
this.setSsn(s);
this.setName(n);
this.setAge(i);
}
// etc.
}
posted on 2009-12-06 22:19 yuxh 閱讀(229) 評論(0) 編輯 收藏 所屬分類: jdk