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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| package com.homework13;
public class Homework13 { public static void main(String[] args) { Teacher teacher1 = new Teacher("王芳", '女', 39, 10); Student student1 = new Student("李明", '男', 19, 222333); Person[] personArray = new Person[4]; personArray[0] = teacher1; personArray[1] = student1; personArray[2] = new Teacher("王", '男', 59, 10); personArray[3] = new Student("李", '女', 19, 333222); Tool tool = new Tool(); tool.sort(personArray); for(Person person : personArray) { System.out.println(person.toString()); tool.play(person); }
} }
class Tool { public void sort(Person[] personArray) { Person temp = null; for (int i = 0; i < personArray.length - 1; i++) { for (int j = 0; j < personArray.length - 1 - i; j++) { if(personArray[j].getAge() < personArray[j + 1].getAge()) { temp = personArray[j]; personArray[j] = personArray[j + 1]; personArray[j + 1] = temp; } } } }
public void play(Person person) { if(person instanceof Teacher) { Teacher teacher = (Teacher) person; teacher.play(); } else if(person instanceof Student) { Student student = (Student) person; student.play(); } else { System.out.println("Fail to play!!"); } } }
class Person { private String name; private char sex; private int age;
public Person(String name, char sex, int age) { this.name = name; this.sex = sex; this.age = age; }
public String toString() { return "姓名:" + this.name + "\n" + "年龄:" + this.age + "\n" + "性别:" + this.sex + "\n"; }
public void play() { System.out.println("play"); }
public String getName() { return name; }
public int getAge() { return age; }
public char getSex() { return this.sex; }
}
class Teacher extends Person { private int workAge;
Teacher(String name, char sex, int age, int workAge) { super(name, sex, age); this.workAge = workAge; }
public String toString() { return "老师的信息:\n" + super.toString() + "工龄: " + this.workAge; }
public void play() { System.out.println("teacher play"); }
public int getWorkAge() { return workAge; } }
class Student extends Person { private int id; Student(String name, char sex, int age, int id) { super(name, sex, age); this.id = id; } public String toString() { return "学生的信息:\n" + super.toString() + "学号: " + this.id; }
public void play() { System.out.println("student play"); } public int getId() { return id; } }
|