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.

Objects and Classes

I made a Bill class that uses a Money class and a Date class. I used the driver bellow and noticed that after I change the amount and dueDate following the first set of println statements, that all three objects(bill1, bill2, and bill3) get the values. Is there any way to prevent this?

Re: Objects and Classes

after I change the amount and dueDate following the first set of println statements, that all three objects(bill1, bill2, and bill3) get the values. Is there any way to prevent this?

Yes, don't change amount or dueDate.

It is important to realise that these variables (and others like them in Java) are references (or pointers) to objects. If you pass such references around as you do by using them in the two constructors and, indirectly, in the copy constructor then everything ends up with references to one and the same amount, and one single due date. So when you change the amount of money of the object amount points to everything with a reference to that object will see the change.

If you want another amount, construct a new Money object.

---

This behaviour is quite normal. And it leads people to write classes in such a way that the amount of money represented by a Money instance can't be changed. (Countries have much the same attitude towards their paper currency.) Such classes are called "immutable" and are very common: methods are simply not provided to change their "state".