Java中对象的对象范围

时间:2010-10-14 01:00:28

标签: java constructor scope

我正在学习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)
  }
}

有解决方法吗?或者我是否需要重新考虑我的设计?

4 个答案:

答案 0 :(得分:3)

您正在构造函数中创建一个新的bookedBy用户变量,而不是使用您的类'成员变量。

您可能想要更改:

user bookedBy = new user(bookedByUsername);

使用:

bookedBy = new user(bookedByUsername);

答案 1 :(得分: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) 
  }
}

答案 2 :(得分:1)

在您的预订课程中,您实际上已经声明了两个名为user 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)
  }
}

答案 3 :(得分: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)
  }
}