-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
86 lines (70 loc) · 2.16 KB
/
Main.java
File metadata and controls
86 lines (70 loc) · 2.16 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
79
80
81
82
83
84
85
86
// Abstract class showing Abstraction
abstract class Student {
// Encapsulation: private fields
private String name;
private int age;
private String studentId;
// Constructor
public Student(String name, int age, String studentId) {
this.name = name;
this.age = age;
this.studentId = studentId;
}
// Getters and Setters (Encapsulation)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStudentId() {
return studentId;
}
// Abstract method (Abstraction)
public abstract void study();
// Common method (can be overridden)
public void printDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Student ID: " + studentId);
}
}
// Subclass demonstrating Inheritance and Polymorphism
class EngineeringStudent extends Student {
private String branch;
public EngineeringStudent(String name, int age, String studentId, String branch) {
super(name, age, studentId);
this.branch = branch;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
// Method overriding (Polymorphism)
@Override
public void study() {
System.out.println(getName() + " is studying engineering concepts.");
}
@Override
public void printDetails() {
super.printDetails();
System.out.println("Branch: " + branch);
}
}
// Main class to run
public class Main {
public static void main(String[] args) {
// Polymorphism: Parent class reference, child class object
Student student = new EngineeringStudent("Bhavneet", 21, "ENG123", "Computer Science");
student.study(); // Calls overridden method
student.printDetails(); // Calls overridden method with super
}
}