网站建设教育平台,域名空间网站建设要多少钱,广州seo关键词,网站开发人员资质问题
我正在阅读有关Java中的接口的文章。其中提到我们必须实现compareTo方法才能在ArrayList容器上调用sort#xff0c;例如Employee类应该实现 Comparable接口。
后面解释了为什么Employee类不能简单地提供compareTo方法而不实现Comparable接口#xff1f;之所以需要接口…问题
我正在阅读有关Java中的接口的文章。其中提到我们必须实现compareTo方法才能在ArrayList容器上调用sort例如Employee类应该实现 Comparable接口。
后面解释了为什么Employee类不能简单地提供compareTo方法而不实现Comparable接口之所以需要接口是因为Java编程是强类型的。在进行方法调用时编译器需要能够检查该方法是否确实存在。
因此当我不实现Comparable接口并使用Arrays.sort方法时我预计会出现编译时错误但我没有观察到编译错误而是得到了运行时错误。请解释为什么上述场景中没有显示编译时错误
以下是代码片段
package com.vrk.inheritance;import java.time.*;
import java.util.Arrays;public class Employee
{private String name;private double salary;private LocalDate hireDay;public Employee(String name, double salary, int year, int month, int day){this.name name;this.salary salary;hireDay LocalDate.of(year, month, day);}public String getName(){return name;}public double getSalary(){return salary;}public LocalDate getHireDay(){return hireDay;}public void raiseSalary(double byPercent){double raise salary * byPercent / 100;salary raise;}/*public int compareTo(Object otherObject) {System.out.println(Employee compareTo called);return 0;}*//*** equalTo function in employee. Created on 8th Sep 2024* param another object to compare to this object*/public boolean equals(Object otherObject) {// quick test to check if objects are identicalif ( this otherObject) return true;// must return false if the explicit parameter is nullif(otherObject null) return false;// if the classes dont match, they cant be equalif (getClass() ! otherObject.getClass()) return false;// now we know otherObject is a non-null Employeevar other (Employee) otherObject;// test whether the fields have identical value// Not sure in my setup below line is not working, but online compiler it is working. // java.util.Objects.equals(this.hireDay, other.hireDay);return true;}public static void main(String[] args) {var staff new Employee[3];// fill the staff array with Manager and Employee objectsstaff[0] new Employee(Harry Hacker, 50000, 1989, 10, 1);staff[1] new Employee(Tommy Tester, 40000, 1990, 3, 15);staff[1] new Employee(Ravi Tester, 60000, 1999, 4, 16);Arrays.sort(staff);}
}解答
如果你看一下的文档Arrays.sort你会发现它根本没有使用泛型它只需要一个Object[]。这就是为什么你不会收到编译错误的原因。
这是出于历史原因该方法是在Java引入泛型之前编写的
如果我们必须能够调用在类中实现的方法为什么我们还必须实现接口?
因为该方法必须进行一些非平凡的反射。将Object转换为Comparable要容易得多而且正如您所指出的这更符合Java的类型系统理念。从本质上讲Java不实现鸭子类型。