Constructor

Initialize box

class box
{
double weight;
double height;
double depth;

double volume()
{
return weight*height*depth;
}
box()
{
weight =10;
height= 20;
depth = 10;
}
}
class boxdemo4
{
public static void main( String args[])
{
box myobj1 = new box();
box myobj2 = new box();
double vol1,vol2;
vol1=myobj1.volume();
vol2=myobj2.volume();
System.out.println(“Volume of box1 is ” + vol1);
System.out.println(“Volume of box1 is ” + vol2);
}
}

 Parameterized constructor

class box
{
double weight;
double height;
double depth;

double volume()
{
return weight*height*depth;
}
box(double w,double h ,double d )
{
weight = w;
height= h;
depth = d;
}
}
class boxdemo5
{
public static void main( String args[])
{

box myobj1 = new box(10.0,20.0,10.0);
box myobj2 = new box(10.0,13.0,10.0);
double vol1,vol2;
vol1=myobj1.volume();
vol2=myobj2.volume();
System.out.println(“Volume of box1 is ” + vol1);
System.out.println(“Volume of box1 is ” + vol2);
}
}

Copy Constructor

Class Distance
{ int x,y;
Distance(int x, int y) { this.x = x; this.y = y; }
Distance(Distance p)
{ this.x = p.x; this.y = p.y ; }
double distancefromorigin()
{ return Math.sqrt(x*x + y*y); }
}
Class DistanceDemo
{
public static void main(String[] args)
{
Distance p = new Distance(4,3);
System.out.println(p.distancefromorigin());
Distance q = new Distance(p);
System.out.println(q.distancefromorigin());
}
}
Output
5.0
5.0

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.