-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructor.java
More file actions
73 lines (64 loc) · 2.12 KB
/
Constructor.java
File metadata and controls
73 lines (64 loc) · 2.12 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
70
71
72
public class Constructor {
public static void main(String args[]) {
Student s1 = new Student();
// Student s2 = new Student(" sakshi");
// Student s3 = new Student(123);
s1.name= "sahu";
s1.roll = 423;
s1.password ="sdfsf";
s1.marks[0]=100;
s1.marks[1]=90;
s1.marks[2]=80;
Student s2 = new Student(s1);//copy
s2.password = "fds";
s1.marks[2]=100;
// reference copy
for(int i=0; i<3; i++){
System.out.println(s2.marks[i]);
}
}
}
class Student{
String name;
int roll;
String password;
int marks[];
// shallow copy constructor
// Student(Student s1){
// marks= new int[3];
// this.name = s1.name;
// this.roll = s1.roll;
// this.marks=s1.marks;
// }
//deep copy constructor
Student (Student s1){
marks = new int [3];
this.name = s1.name;
this.roll = s1.roll;
for(int i=0; i<marks.length; i++){
this.marks[i]=s1.marks[i];
}
}
// non parametrized
Student() {
marks= new int[3];
System.out.println("sakshi");
}
// parametrized
Student(String name){
marks= new int[3];
this.name = name;
}
Student(int roll){
marks= new int[3];
this.roll = roll;
}
}
//type of constructor
//1. non parameterized
//2. parameterized
//3. copy constructor
//default constructor gets called during the time of object creation and its job is to intialse the member variables with the default value of their datatype.
// default constructor is a special method that has the same name as the class name it can have parameter list , it can also have return type but we don't specify the return type .
//in the default constructor JVM intialize the default value of the datatype.
// destructor: there is a garbage collector so there is no need to destructor any code.