4 Copy Constructor is a constructor that takes the object of same class as argument.
4 If all the properties of an object has to be assigned to another object, this is advisable.
Example:
class distance
{
private int feet;
private float inch;
distance()
{
}
distance(int f, float i)
{
feet=f;
inch=i;
}
distance( distance k)
{
feet=k.feet;
inch=k.inch;
}
}
class Test
{
public static void main(String as[])
{
distance d1=new distance(3, 4.5);
distance d2=new distance(d1);
}
}
Explanation:
4 In the above example, there are three constructors: constructor without arguments, constructor with two arguments and a copy constructor.
4 Copy constructor is called for the object “d2” and all the properties of “d1” will be copied to the properties of “d2”. So, “d2” holds “3” and “4.5” as its “feet” and “inch”.
0 comments:
Post a Comment