Results 1 to 5 of 5
  1. #1
    guest_user is offline Member
    Join Date
    May 2011
    Posts
    47
    Rep Power
    0

    Default On references and copy constructors

    If I have a private member reference to an object in my class, do I have to override the copy constructor such that when it is invoked, the object itself is copied and not the reference?

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default

    I don't think Java has a copy constructor. Copies are made by using the Object class's clone method.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default

    Quote Originally Posted by Norm View Post
    I don't think Java has a copy constructor. Copies are made by using the Object class's clone method.
    It does have the concept, since it is after all simply a constructor that takes an object of the same class as a parameter and copies the data.

    To the OP, you would need to copy the child objects as well.
    This means they would need to be either Cloneable or themselves have valid copy constructors.

    This is the difference between a shallow copy (which simply copies the values as is) and a deep copy.

    Though I would suggest you really think through what you're doing and ensure you do need to be copying.

  5. #5
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,436
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by guest_user View Post
    If I have a private member reference to an object in my class, do I have to override the copy constructor such that when it is invoked, the object itself is copied and not the reference?
    The fact 'private' counts on a class basis; you can do this:

    Java Code:
    public class T {
       private U yourPrivateObject;
       public T(T t) { // copy ctor
          this.yourPrivateObject= // copy of t.privateObject;
       }
    }
    It's up to you how to copy the private object u.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Replies: 0
    Last Post: 12-28-2007, 12:25 PM
  2. Soft References
    By rickcharles_b in forum Advanced Java
    Replies: 0
    Last Post: 06-20-2007, 08:27 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •