2010-10-14 135 views
0

我正在學習Java,所以我希望這個問題不太明顯。我來自另一種沒有垃圾收集的語言。 在這種其他語言中,我有時會在構造函數中創建對象,然後在析構函數中將它們刪除,以便可以在對象的整個生命週期中使用它們。Java中的對象範圍內的對象範圍

作爲一個簡單的例子,我有一個用戶和一個預訂類。預訂類引用了用戶,但是如果我在預訂類的構造函數中創建用戶,那麼它會在用戶離開構造函數並超出作用域時將其解引用。以後任何對booking.bookedBy用戶的引用調用都會返回null。

class user { 
    public String username; 
    public String displayName; 
    user(Connection conn, String usernameIn){ 
    username = usernameIn; 
     ... do DB stuff to populate attributes 
    } 
} 

class booking { 
    int bookingID; 
    user bookedBy; 
    ... 
    booking(Connection conn, int bookedIDIn){ 
    bookingID = bookedIDIn; 
     ...do DB stuff to populate attributes and grab bookedByUserID 
     ...field value and build the BookedByUsername 
    user bookedBy = new user (bookedByUsername) 
    } 
} 

有沒有辦法解決這個問題?還是我需要重新考慮我的設計?

+0

請不要使用小寫的類名。 – Thilo 2010-10-14 01:33:44

+0

採取的措施 - 我會盡量符合。是否有標準的命名約定記錄在任何地方?另一個我更喜歡不區分大小寫的語言的原因。 – Peter 2010-10-14 07:02:45

+0

http://www.oracle.com/technetwork/java/codeconv-138413.html – 2010-10-14 14:27:05

回答

3

你在你的構造函數創建一個新的bookedBy用戶變量,而不是使用你的類的成員變量。

你可能想改變:

user bookedBy = new user(bookedByUsername);

有:

bookedBy = new user(bookedByUsername);

+0

優秀的作品。顯示我使用Java的經驗不足。我想我使用德爾福在那裏你聲明方法的頂部的所有本地變量。感謝指針。 – Peter 2010-10-14 01:28:03

2

你在你的構造函數中聲明瞭一個局部變量,它被用來分配你在構造函數中創建的用戶。

我想你想要這樣的:

class booking { 
    int bookingID; 
    user bookedBy; 
    ... 
    booking(Connection conn, int bookedIDIn){ 
    bookingID = bookedIDIn; 
    //there's no declaration of type needed here because 
    //you did that earlier when you declared your member variable up top. 
    bookedBy = new user (bookedByUsername) 
    } 
} 
+0

或者,如果您的口味以這種方式運行,那麼可避免含糊不清的Python-infuenced'this.bookedBy = ...'。 – bobince 2010-10-14 01:11:18

+0

好主意。我可能會使用「this」,特別是當我使用該語言時。 – Peter 2010-10-14 01:29:21

1

在預訂類,你實際上已經宣佈了兩個變量稱爲用戶bookedBy。一個有整個預訂類的範圍,一個有構造函數的範圍。爲了解決這個問題,你需要刪除的變量聲明在構造函數,如下所示:

class booking { 
    int bookingID; 
    user bookedBy; 
    ... 
    booking(Connection conn, int bookedIDIn){ 
    bookingID = bookedIDIn; 
     ...do DB stuff to populate attributes and grab bookedByUserID 
     ...field value and build the BookedByUsername 
    bookedBy = new user (bookedByUsername) 
    } 
} 
1
user bookedBy; 

user bookedBy = new user (bookedByUsername) 

是兩個不同的變量。

刪除第二個類型聲明並將您的用戶實例分配給字段級別。即:

class booking { 
    int bookingID; 
    user bookedBy; 
    ... 
    booking(Connection conn, int bookedIDIn){ 
    bookingID = bookedIDIn; 
     ...do DB stuff to populate attributes and grab bookedByUserID 
     ...field value and build the BookedByUsername 
    bookedBy = new user (bookedByUsername) 
    } 
}