5 changed files with 87 additions and 0 deletions
@ -0,0 +1,21 @@ |
|||
public abstract class Person { |
|||
protected String name; |
|||
protected int age; |
|||
|
|||
public Person(String name, int age) { |
|||
this.name = name; |
|||
this.age = age; |
|||
} |
|||
|
|||
public String getName() { return name; } |
|||
public int getAge() { return age; } |
|||
|
|||
public abstract String getRole(); |
|||
public abstract String getExtraInfo(); |
|||
|
|||
@Override |
|||
public String toString() { |
|||
return getRole() + " | Name: " + name + ", Age: " + age |
|||
+ ", " + getExtraInfo(); |
|||
} |
|||
} |
|||
@ -0,0 +1,30 @@ |
|||
import java.util.ArrayList; |
|||
import java.util.List; |
|||
|
|||
public class SchoolSystem { |
|||
private List<Person> personList = new ArrayList<>(); |
|||
|
|||
// 统一的 addPerson 方法,替代原来的 addStudent / addTeacher
|
|||
public void addPerson(Person p) { |
|||
personList.add(p); |
|||
System.out.println("Added: " + p); |
|||
} |
|||
|
|||
public void listAll() { |
|||
System.out.println("\n--- All Members ---"); |
|||
for (Person p : personList) { |
|||
System.out.println(p); |
|||
} |
|||
} |
|||
|
|||
public static void main(String[] args) { |
|||
SchoolSystem system = new SchoolSystem(); |
|||
|
|||
system.addPerson(new Student("Alice", 20, "S001", 3.8)); |
|||
system.addPerson(new Student("Bob", 19, "S002", 3.5)); |
|||
system.addPerson(new Teacher("Mr. Chen", 35, "Math", 10)); |
|||
system.addPerson(new Teacher("Ms. Li", 28, "English", 4)); |
|||
|
|||
system.listAll(); |
|||
} |
|||
} |
|||
@ -0,0 +1,18 @@ |
|||
public class Student extends Person { |
|||
private String studentId; |
|||
private double gpa; |
|||
|
|||
public Student(String name, int age, String studentId, double gpa) { |
|||
super(name, age); |
|||
this.studentId = studentId; |
|||
this.gpa = gpa; |
|||
} |
|||
|
|||
@Override |
|||
public String getRole() { return "Student"; } |
|||
|
|||
@Override |
|||
public String getExtraInfo() { |
|||
return "ID: " + studentId + ", GPA: " + gpa; |
|||
} |
|||
} |
|||
@ -0,0 +1,18 @@ |
|||
public class Teacher extends Person { |
|||
private String subject; |
|||
private int yearsOfExperience; |
|||
|
|||
public Teacher(String name, int age, String subject, int yearsOfExperience) { |
|||
super(name, age); |
|||
this.subject = subject; |
|||
this.yearsOfExperience = yearsOfExperience; |
|||
} |
|||
|
|||
@Override |
|||
public String getRole() { return "Teacher"; } |
|||
|
|||
@Override |
|||
public String getExtraInfo() { |
|||
return "Subject: " + subject + ", Experience: " + yearsOfExperience + " years"; |
|||
} |
|||
} |
|||
Binary file not shown.
Loading…
Reference in new issue