Java中对象内的对象范围 [英] Scope of object within an object in Java

查看:151
本文介绍了Java中对象内的对象范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,所以我希望这个问题不是太明显。我来自另一种语言,没有垃圾收集。
在这种其他语言中,我有时在构造函数中创建对象,然后在析构函数中删除它们,以便我们可以在对象的整个生命周期使用它们。

I'm learning Java at the moment so I hope this question isn't too obvious. I come from another language which does not have garbage collection. In this other language I sometimes created objects in constructor and then deleted them in the destructor so I could use them for the entire life of the object.

As一个简化的例子,我有一个用户和一个预订类。预订类引用了一个用户,但是如果我在预订类的构造函数中创建用户,则它会在用户离开构造函数并且超出范围时解除引用。任何未来对booking.bookedBy用户的引用调用都返回null。

As a simplified example, I have a user and a booking class. The booking class references a user but if I create the user in the constructor of the booking class, it dereferences the user once it leaves the constructor and becomes out of scope. Any future reference call to the booking.bookedBy user then returns 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)
  }
}

有办法吗?

推荐答案

您正在创建一个新的 bookedBy

You are creating a new bookedBy user variable in your constructor, rather than using your class' member variable.

您可能想要更改:

用户bookedBy =新用户(bookedByUsername);

with:

bookedBy =新用户(bookedByUsername);

这篇关于Java中对象内的对象范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆