2012-02-25 46 views
-1

您好,我正在使用Java進行LinkedList項目,我在腦海中有一些不清楚的問題。例如,這是我的「患者」類;在Java中使用「new」關鍵字創建對象或不使用「new」創建對象

public class Patient { 

private int id; 
private String name; 
private String lastName; 
private String doctor; 

private Patient next; 
private Patient prev; 

public Patient(int id, String name, String lastName, String doctor, Patient next, Patient prev){ 

    this.id = id; 
    this.name = name; 
    this.lastName = lastName; 
    this.doctor = doctor; 
    this.next = next; 
    this.prev = prev; 

} 

當我構建我的LinkedList我創建一個這樣的頭和尾節點。

private Patient header = new Patient(0, null, null, null, null, null); 
private Patient tail = new Patient(0, null, null ,null ,null, null); 

,但如果我不創造任何new Patient(0, null, null, null, null, null);並沒有改變這兩個節點。你能解釋爲什麼嗎?

+3

你是什麼意思「創建沒有新節點」?你究竟做了什麼?什麼不改變? – 2012-02-25 21:45:34

+0

我的意思是如果我只使用「私人患者標題」;程序工作same_ ?. – quartaela 2012-02-25 21:49:13

+1

我是否需要求你完全解釋自己?無論如何,如果你只是寫私人Patient頭;你聲明一個Patient類型的對象的引用,它現在指向null。如果你永遠不把它分配給任何東西,但不要試圖解引用它(使用它,比如調用它的實例方法),你的程序將「工作」。 – 2012-02-25 21:51:47

回答

1

不使用新關鍵字時,您會得到空引用。您是否嘗試訪問並使用未使用新關鍵字實例化的對象進行操作? 添加一個名爲getName()的方法,並在實例化之前在Patient變量上調用它。這將導致「空指針異常」

+0

是的,我得到nullpointerexception。現在我懂了。非常感謝你 :) – quartaela 2012-02-25 21:55:06

相關問題