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.

I'm seriously need help to understand the concept of making shallow copies and deep copies. My book has shown me that its better to perform deep copies and I have followed that method. if you guys look in my constructor of the cash class

when I pass in an argument from my demo, I'm making a copy of that object from the demo class.

In my retail class, I have the following copy constructor

//Make a copy constructor
public Retail(Retail Object1)
{
Item_Name=Object1.Item_Name;
Item_Number=Object1.Item_Number;
// if I use this then my program would work//this.cost=Object1.cost;
//if I use this part of code below, my program won't work at all and I would get an error saying Exception in thread "main" java.lang.NullPointerException
this.cost.Item_Cost=Object1.cost.Item_Cost;
this.cost.Wholesale_Cost=Object1.cost.Wholesale_Cost;
}

My question is why can't I perform a deep copy there. I know if I do

this.myRetail=myRetail

in my cash constructor it would work, but then the book says its not a good method; however, even my teacher uses this so I'm confused here wahts going on.

Re: Copying objects through constructors?

This:

this.cost.Item_Cost=Object1.cost.Item_Cost;

is an odd looking statement. Is there a Cost class? If so, please show the whole Retail and Cost classes. If there is not a Cost class, specify what cost, Item_cost, and Wholesale_Cost are. (The correct naming per Java convention should be itemCost and wholesaleCost.)