I have a class named Cash shown belowpublic class Cash { //Quanity Field and RetailItem Object field private int total_units; private Retail myRetail; //Create first constructors public Cash() { this(0,null); } //Second constructor public Cash(int total_units) { this(total_units,null); } //Create third constructor public Cash(Retail myRetail) { this(0,myRetail); } //Create a a constructor public Cash(int total_units,Retail myRetail) { this.total_units=total_units; this.myRetail=new Retail(myRetail); }
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//Create a a constructor public Cash(int total_units,Retail myRetail) { this.total_units=total_units; this.myRetail=new Retail(myRetail);
Apparently I have field in Cash Class namedwhen I pass in an argument from my demo, I'm making a copy of that object from the demo class.Retail myRetail
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 doin 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.this.myRetail=myRetail