JAVA4. 使用JDK中的接口。对继承多态作业1中的学生类(Student)进行扩展,重写方法toString,equal;实现接口Comparable,按照学号大小进行比较;定义构造Z方法。并在测试中使用Arrays.sort方法对一个学生对象数组进行排序,体会多态。
时间: 2024-02-11 14:07:59 浏览: 74
首先,我们需要在Student类上实现Comparable接口,实现compareTo方法,按照学号大小进行比较:
```java
public class Student implements Comparable<Student> {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return id == student.id && age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
@Override
public int compareTo(Student o) {
return Integer.compare(this.id, o.id);
}
}
```
然后,我们需要在测试中创建一个学生对象数组,并使用Arrays.sort方法对其进行排序:
```java
public class Test {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student(3, "Tom", 18);
students[1] = new Student(1, "Lucy", 19);
students[2] = new Student(2, "Jack", 20);
Arrays.sort(students);
for (Student student : students) {
System.out.println(student);
}
}
}
```
输出结果:
```
Student{id=1, name='Lucy', age=19}
Student{id=2, name='Jack', age=20}
Student{id=3, name='Tom', age=18}
```
可以看到,使用多态的方式调用了Arrays.sort方法,并且按照学号大小进行了排序。
阅读全文