【问题标题】:Scope of object within an object in JavaJava中对象内的对象范围
【发布时间】: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


【解决方案1】:

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

你可能想要改变:

user bookedBy = new user(bookedByUsername);

与:

bookedBy = new user(bookedByUsername);

【讨论】:

  • 非常好用。显示我使用 Java 的经验不足。我想我已经习惯了 Delphi,您在方法顶部声明所有局部变量。感谢您的指针。
【解决方案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) 
  }
}

【讨论】:

  • 或者,如果你的口味是这样,受 Python 影响的this.bookedBy=...,它可以避免歧义。
  • 好主意。我可能会使用“this”,尤其是当我习惯了这种语言时。
【解决方案3】:

在您的预订类中,您实际上已经声明了两个变量,称为用户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)
  }
}

【讨论】:

    【解决方案4】:
     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)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 2017-06-05
      • 2013-06-07
      • 2021-02-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多