構(gòu)造函數(shù)的一些用法
We may wish to instantiate additional objects related to the Student object:
初始化與對(duì)象相關(guān)的一些額外對(duì)象:
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.
}
}
讀取數(shù)據(jù)庫(kù)來初始化對(duì)象屬性:
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.
}
和其他已存在的對(duì)象交流:
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.
}
好習(xí)慣:如果需要有參數(shù)的構(gòu)造函數(shù),最好同時(shí)顯示聲明一個(gè)無(wú)參構(gòu)造函數(shù)。
容易出現(xiàn)的bug:如果給構(gòu)造函數(shù)加上void編譯會(huì)通過!不過會(huì)被當(dāng)作方法而不是構(gòu)造函數(shù)!
當(dāng)有多個(gè)構(gòu)造函數(shù),而且都有共同的初始化內(nèi)容時(shí),就會(huì)出現(xiàn)很多重復(fù)的代碼,比如構(gòu)造一個(gè)新學(xué)生,我們會(huì)做:
1 通知登記辦公室學(xué)生的存在
2 給學(xué)生創(chuàng)建學(xué)生成績(jī)報(bào)告單
重復(fù)引起以后修改必須修改多處,如果使用this 會(huì)得到改善
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) 評(píng)論(0) 編輯 收藏 所屬分類: jdk