This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor basics

 
ppavya india
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I need some help in the program given below.This program contents some constructor basics, but I haven't understood two method and some statements, could you please explain me what are they.I have marked those methods and statements with comments as //didn't get******************
Any help would be appreciated.
Thanx in advance
class box
{
int l,b,h;
box(int i)
{
l=b=h=i;
}
box(int l, int b, int h)
{
this.l=l;
this.b=b;
this.h=h;
}
box (box b)//didn't get****************************************
{
this.l=b.l;
this.b=b.b;
this.h=b.h;
}

public void volume()
{
System.out.println(l*b*h);
}
public static box clone(box b)//didn't get********************
{
return new box (b.l,b.b,b.h);//didn't get***********************
}
}
class test
{
public static void main(String ab[])
{
box b2,b3,b4,b5;
b2=new box(10);
b3=new box(10,20,30);
b2.volume();
b3.volume();
System.out.println("After creating a clone");
//b4=box.clone (b2); //didn't get************************
//or
b4=new box(b2);
b4.volume();
//b5=box.clone(b3);//didn't get***************************
//or
b5=new box(b3);
b5.volume();
}
}
 
David Ulicny
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
box (box b) this is called copy constructor. It take as parameter itself type and do some action on that instance, which produces the copy of that object. I was using this in C++ because of pointers. C++ has implicit copy constructor but this one did only the shallow copy, it means only copy of pointers no copy of data.
Here it is the same situation, you do a clone of some object. You want it will have the same property as the old one.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic