我一直在試圖圍繞OOD包裹頭部而感到沮喪。我試圖建立一個有三個類的程序 - 一個叫Person,它有一個由個人信息組成的構造器。另一個名爲Doctor的類繼承了Person類,只是構造一個帶有額外字段(大部分字段,即名稱,地址將指向person對象)稱爲專業的對象。我使用另一個類來構建Java應用程序來創建,查看和修改人員和醫生對象中的字段。從構造函數構造鏈接的Java對象
我已經構建了人員和醫生類,你可以在這篇文章的底部找到他們的相關代碼。當我嘗試創建醫生對象時,會出現問題,因爲我的代碼似乎在創建與人物無關的全新醫生對象。我試圖編輯人物對象的firstName字符串,但醫生對象沒有更新以反映它。它似乎創建了它自己的永久名稱,而不是簡單地指向person對象中定義的名稱。
我通過用戶輸入創建人物對象並使用以下行存儲它們。
persons[amountPersons] = new Person (firstName, lastName, homeAddress, phoneNumber);
amountPersons++;
一個人一旦對象被創建,用戶可以輸入personNumber創造像這樣
person = getPersonID(personID);
int personNumber;
String firstName = null;
String lastName = null;
String homeAddress = null;
String phoneNumber = null;
firstName = person.firstName;
lastName = person.lastName;
homeAddress = person.homeAddress;
phoneNumber = person.phoneNumber;
personNumber = person.personNumber;
System.out.print ("Enter speciality of the doctor: ");
String speciality = input.nextLine();
doctors[amountDoctors] = new Doctor (firstName, lastName, homeAddress, phoneNumber, speciality);
amountDoctors++;
這到底我做錯了醫生的對象?對大量代碼表示歉意 - 我儘可能地減少了代碼,但我不確定問題出在哪裏,所以我只能這麼做。
Person類
public class Person {
//Instance Variables
protected String firstName;
protected String lastName;
protected String homeAddress;
protected String phoneNumber;
protected int personNumber;
private static int NumberSystem = 1;
public Person()
{
firstName = " ";
lastName = " ";
homeAddress = " ";
phoneNumber = " ";
personNumber = 0;
}
public Person (String firstName, String lastName, String homeAddress, String phoneNumber)
{
// Initialize instance variables
this.firstName = firstName;
this.lastName = lastName;
this.homeAddress = homeAddress;
this.phoneNumber = phoneNumber;
personNumber = NumberSystem;
NumberSystem = NumberSystem + 1;
}
public String toString()
{
String p;
p = "=================================================" +"\n" +
"Identification Number: " + personNumber +"\n" +
"Name: " + firstName +"\n" +
"Surname: " + lastName +"\n" +
"Address: " + homeAddress +"\n" +
"Mobile/Telephone: " + phoneNumber +"\n";
return p;
}
醫生
public class Doctor extends Person{
// the aim of Doctor subclass is to simply add a speciality field
private String speciality;
int doctorID;
public Doctor() {
doctorID = 0;
speciality = "none";
}
public Doctor(String firstName, String lastName, String homeAddress, String phoneNumber, String speciality) {
super(firstName, lastName, homeAddress, phoneNumber);
this.speciality = speciality;
}
public String toString()
{
String d;
d = "=================================================" +"\n" +
"Doctor Number: " + doctorID +"\n" +
"Person Number: " + personNumber +"\n" +
"Name: " + firstName +"\n" +
"Surname: " + lastName +"\n" +
"Address: " + homeAddress +"\n" +
"Mobile/Telephone: " + phoneNumber +"\n" +
"Speciality: " + speciality +"\n";
return d;
}
}
它對我來說就像你不尋找繼承,但組成。目前,當你有'Doctor'時,它也是'Person',這意味着你可以在任何可以使用'Person'的地方使用它。儘管如此,它並沒有將其鏈接到任何其他的「Person」對象。要做到這一點,您需要讓'Doctor'擁有'Person'字段,而不是將其作爲子類。 – Dragondraikk