【发布时间】:2011-04-25 03:55:36
【问题描述】:
我目前正在学习 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)
}
}
有没有办法解决这个问题?还是我需要重新考虑我的设计?
【问题讨论】:
-
请不要使用小写的类名。
-
要点——我会尽量遵守。是否有任何地方记录的标准命名约定?我更喜欢不区分大小写的语言的另一个原因。
标签: java constructor scope