-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathConstructorOverloading.java
More file actions
69 lines (56 loc) · 1.99 KB
/
ConstructorOverloading.java
File metadata and controls
69 lines (56 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package src.learning;
class Box{
double width;
double height;
double depth;
// Contrutor that takes object as parameter
// to create clone of that object
// This construtor is called when an object is passed as a parameter
Box (Box obj){
width = obj.width;
height = obj.height;
depth = obj.depth;
}
// Constructor used when all three sides are specified
Box (double width, double height, double depth){
this.width = width;
this.height = height;
this.depth = depth;
}
// Constructor used when a cube is created i.e speacifying only one side
Box (double len){
this.width = len;
this.height = len;
this.depth = len;
}
// default construtor
Box (){
width = -1; // -1 indicates an uninitialized box
height = -1;
depth = -1;
}
// Method that computes and returns the volume
double volume(){
return width*height*depth;
}
}
class OverloadingCons{
public static void main(String[] args) {
// Creating objects of class Box
// constructor with three parameters is called i.e contructor at line 18
Box box1 = new Box(10, 20, 30);
// default constructor is called i.e construtor at line 32
Box box2 = new Box();
// constructor with 1 param is called i.e constructor at line 25
Box box3 = new Box(10);
// constructor called when another object is passed as parameter
// constructor at line 11 is called
// the object cloneBox1 will have same properties as the box1
Box clonedBox1 = new Box(box1);
// printing volume of all boxes
System.out.println("Volume of box1 = "+ box1.volume());
System.out.println("Volume of box2 = "+ box2.volume());
System.out.println("Volume of box3 = "+ box3.volume());
System.out.println("Volume of clonedBox1 = "+ clonedBox1.volume()+" which is same as volume of box1");
}
}