Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: An associations with copies instead of references

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default An associations with copies instead of references

    I know this might not be a general Java question - but I'm also looking for an alternative if anyone can relate to it.

    To put it simple, I have a unidirectional association between a class (DailyManagement) and another class (Manko).

    Let's pretend the below UML-Diagram is correct, just to give you an idea of what I'm trying to achieve:



    The special thing is that DailyManagement doesn't contain references to Manko objects as it usually is, it contains copies of the objects.

    The idea is that you create a DailyManagement object every day, and on the time of creation you copy the instances of the Mankos as they are at that time - so when you change the Mankos later on, it will not affect the Mankos in the previous objects of DailyManagement.

    My question is, what type of link between those classes is this called?
    Last edited by Muskar; January 4th, 2011 at 03:26 PM.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: An associations with copies instead of references

    If I understand you correctly, that type of association is known as "pass by value".

    When you pass by value, the two objects physically exist in different places (depending on how deep your copy is, they could be completely separate or they could share some object deep down). In C++, this is generally done using something known as the "Copy constructor" to make a new copy of the old object in memory.

    Pass by reference is where only the address of the object gets passed and any changes made at that address gets reflected in all references to that same object.

    In Java all objects are passed by reference and all primitives are passed by value (arrays are passed by reference regardless of what type of objects they contain). You can simulate the pass by value concept by implementing the Cloneable interface (you'll need to implement a deep copy of all sub-objects, though for Strings this isn't a problem since they're immutable).

    However, you will still need to be careful about modifying the object if you get it from DailyManagement:

    Anytime you want to "retrieve" a Manko object from DailyManagement you're actually getting the reference and any changes you make to that object will be reflected in the Manko object pointed to from DailyManagement because they are the same object.
    Last edited by helloworld922; January 4th, 2011 at 08:25 PM.

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: An associations with copies instead of references

    Java does not pass Objects by reference. Everything in Java is passed by value. Recommended reading: JavaRanch Campfire - Pass By Value, Please

    Java does support copy constructors, you just have to write them.

    Basically, if you want your Object to contain copies of some other Object, simply make a copy of that second Object. You'll have to write the code that does this, either by a copy constructor (or method), or by using the Cloneable interface.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: An associations with copies instead of references

    Java doesn't support copy constructors in the same way C/C++ supports them, but yes, you can write a constructor in Java which will take an object of the same type and construct all the fields back.

    // really C++ code
    #include <iostream>
    using namespace std;
     
    class Point
    {
    public:
    	double x, y;
     
    	Point()
    	{
    		cout << "default constructor" << endl;
    	}
     
    	Point(double x, double y)
    	{
    		cout << "in the main constructor" << endl;
    		this->x = x;
    		this->y = y;
    	}
     
    	Point(Point& p)
    	{
    		cout << "in the copy constructor" << endl;
    		x = p.x;
    		y = p.y;
    	}
    };
     
    void doit(Point p)
    {
    	cout << "inside doit" << endl;
    }
     
    int main(void)
    {
    	Point p1 = Point(2,3); // main constructor called
    	Point p2 = p1; // copy constructor called
    	Point p3; // default constructor called
    	p3 = p2; // no constructor called, but values of x and y are the same in all 3 points
    	cout << p3.x << " " << p3.y << endl;
    	// p1, p2, and p3 all exist in different places in memory
    	cout << "p1 address: " << &p1 << endl;
    	cout << "p2 address: " << &p2 << endl;
    	cout << "p3 address: " << &p3 << endl;
    	doit(p1);
    	cin.ignore();
    	return 0;
    }

    The copy constructor gets called on:
    1. when initializing a newly declared point (p2). Note that this initialization must take place at the time of declaration otherwise the copy constructor will not be called.
    2. On passing by value to a function.

    In Java, if you tried to define a copy constructor these two properties wouldn't exist. You can think of all Java object variables as C++ pointers, which do not exhibit this pass by value behavior.

    Lastly, I'm not really sure whether it's better (or more acceptable) to implement Cloneable or to implement a pseudo-copy constructor. Either way would basically get you the same thing.

    public class Test implements Cloneable
    {
    	int	a;
     
    	public Test(int a)
    	{
    		this.a = a;
    		System.out.println("default constructor");
    	}
     
    	public Test(Test t)
    	{
    		System.out.println("pseudo copy constructor");
    	}
     
    	public static void doit(Test t)
    	{
    		System.out.println("inside doit");
    	}
     
    	@Override
    	public Test clone()
    	{
    		System.out.println("inside clone method");
    		return new Test(a);
    	}
     
    	public static void main(String[] args)
    	{
    		System.out.println("initializing t1");
    		Test t1 = new Test(1);
    		System.out.println("initializing t2");
    		Test t2 = t1; // copy constructor is not called
    		System.out.println("initializing t3");
    		Test t3 = new Test(t1); // it must be specifically invoked
    		System.out.println("initializing t4");
    		Test t4 = t3.clone(); // calling the clone method can function like the
    								// pseudo copy constructor
     
    		// passing by value must also be done by explicitly calling the copy
    		// constructor
    		System.out.println();
    		doit(t1);
    		System.out.println("doit using pseudo-copy constructor");
    		doit(new Test(t1));
    		System.out.println("doit using clone");
    		doit(t1.clone());
    		// t1 and t2 are the exact same object. t1/t2, t3, and t4 are all
    		// distinct objects
    	}
    }

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: An associations with copies instead of references

    Just in case it isn't clear, I'd like to point out that helloworld922's example copy constructor, clone method, and copy method don't include the code that would really make them copy anything (I think he was just going for the barebones).

    For example, the copy constructor might look something like this:


    public Test(Test t)
        {
            System.out.println("copy constructor");
            this.a = t.;
        }

    Also note that if a were an Object, you'd have to go a level deeper, copying/cloning those Objects, otherwise both copies of Test would contain the same instance of whatever type a is.

    A real life example of a copy method that I like is Graphics.create().

    Graphics (Java Platform SE 6)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: An associations with copies instead of references

    For primitives it doesn't matter. But yes, for objects you will need to call their clone/copy constructors. Additionally, you likely can get away with doing a shallow copy of strings because they're immutable.

Similar Threads

  1. Averaging Numbers in an Array Based on References
    By aussiemcgr in forum Java Theory & Questions
    Replies: 6
    Last Post: August 6th, 2010, 06:39 PM
  2. requir GPS references in java
    By hassan ali in forum Java Theory & Questions
    Replies: 6
    Last Post: July 18th, 2010, 10:34 AM
  3. How to extract a particular element details which has more references ???
    By j_kathiresan in forum Algorithms & Recursion
    Replies: 1
    Last Post: December 31st, 2009, 01:11 AM