-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructorstype.java
More file actions
78 lines (65 loc) · 1.98 KB
/
constructorstype.java
File metadata and controls
78 lines (65 loc) · 1.98 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
73
74
75
76
77
78
class Student {
// Fields
private String name;
private int grade;
// Non-parameterized constructor (No-argument constructor)
public Student() {
this.name = "Unknown";
this.grade = 0;
}
// Parameterized constructor
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
// Copy constructor
public Student(Student student) {
this.name = student.name;
this.grade = student.grade;
}
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for grade
public int getGrade() {
return grade;
}
// Setter for grade
public void setGrade(int grade) {
if (grade >= 0 && grade <= 100) {
this.grade = grade;
} else {
System.out.println("Grade must be between 0 and 100.");
}
}
// Method to display student details
public void display() {
System.out.println("Name: " + name);
System.out.println("Grade: " + grade);
}
}
// Driver class
class Constructorstype {
public static void main(String[] args) {
// Creating an object using the non-parameterized constructor
Student student1 = new Student();
student1.display();
// Creating an object using the parameterized constructor
Student student2 = new Student("Vedik Tiwari", 90);
student2.display();
// Creating a copy of student2 using the copy constructor
Student student3 = new Student(student2);
student3.display();
// Modifying the copied object
student3.setName("Rohan Sharma");
student3.setGrade(85);
student3.display();
// Displaying the original object to show it remains unchanged
student2.display();
}
}