-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJava Constructor
86 lines (76 loc) · 1.83 KB
/
Java Constructor
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
## Welcome to KKEL for Java
# LESSON: Java Constructors
- Rules for creating a Constructor
- Constructor Overloading
- Constructor Chaining
### Rules for creating a Java Constructor
1. It has the same name as the class
2. It should not return a value not even void
### First Constructor Java example
```
class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
d1.display();
}
}
```
Save , Run & Compile the code. Observe the output.
Output:
```
Inside Constructor
Value1 === 10
Value2 === 20
```
### Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter list
#### Examples of valid constructors for class Account are
```
Account(int a);
Account (int a,int b);
Account (String a,int b);
```
#### Example to understand Constructor Overloading
```
class Demo{
int value1;
int value2;
/*Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}*/
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
```