Simple Program
Hi All,
I am not getting the output as expected.
package javaProg.completeReferance;
class Box2
{
doublewidth,height,depth;
Box2()
{
width=0;
height=0;
depth=0;
}
Box2(double width,double height,double depth)
{
this.width=width;
this.height=height;
this.depth=depth;
}
Box2(Box2 clone)
{
clone.width=this.width;
clone.height=this.height;
clone.depth=this.depth;
}
double volume()
{
return this.width*this.height*this.depth;
}
}
publicclass BoxDemo2
{
publicstaticvoid main(String [] args)
{
Box2 object1=new Box2(12,34,56);
Box2 object2 =new Box2();
Box2 object3 =new Box2(object1);
System.out.println("The volume for Object1 is "+object1.volume());
System.out.println("The volume for Object2 is "+object2.volume());
System.out.println("The volume for Object3 is "+object3.volume());
}
}
Right. So now the rest of us can help figure out what might be going wrong.
You just need to fix the constructor that takes a Box2 as a parameter. Look closely at what I pointed out in my first reply. If you don't see what's wrong, then just go ahead and reverse the assignments (make them "this.foo = clone.foo;" instead), and then run it again.
Try to figure out what was going wrong though.
I think it's an interesting bug. You see the 0s and the first thought is probably "hmm, none of the assignments are working" or "something is wrong with volume()".
Thanks All I got the expected output but when i dry run on the old code I am confused.
Lets start from this code.
Box2 object1=new Box2(12,34,56);
This will call the constructor with 3 double argument , after that the object1 instant variable will hold the assigned the values in the parameter.Then when I called the volume method the output was 0 for the respective object.
This looksa bit wired to me as The constructor with double argument has nothing to do with Clone constructor.
Sorry if i am sence less.
> This looksa bit wired to me as The constructor with
> double argument has nothing to do with Clone
> constructor.
I think the problem might have started with the parameter name. With that constructor, "this" *is* the clone of "clone". When the goal is to construct a clone of an existing Box2, I can sympathize with not seeing what is wrong with the line "clone.width = this.width".
If you renamed the parameter to "original", then it will be more intuitive to see that "this.width = original.width" makes more sense than "original.width = this.width".