import java.util.*;
public class Employee
{
private int empId;
private String name;
private int age;
public Employee(String name, int id, int age )
{
this.name = name;
this.empId = id;
this.age = age;
}
public int getId()
{
return empId;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
}
class SortById extends Employee implements Comparable<SortById>
{
public SortById(String name, int id, int age)
{
super(name, id, age);
}
public int compareTo(SortById other)
{
if (this.getId() > other.getId()) return 1;
if (this.getId() < other.getId()) return -1;
return 0;
}
}
class SortByName extends Employee implements Comparable<SortByName>
{
public SortByName(String name, int id, int age)
{
super(name, id, age);
}
public int compareTo(SortByName other)
{
if (this.getName().compareTo(other.getName()) > 0) return 1;
if (this.getName().compareTo(other.getName()) < 0) return -1;
return 0;
}
}
class Test
{
public static void main(String args[])
{
Employee[] array = new SortById[3];
array[0] = new SortById("Gautam", 1222, 20);
array[1] = new SortById("Shivam", 1221, 20);
array[2] = new SortById("Ankit", 1223, 21);
System.out.println(array[0] instanceof SortByName);
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
System.out.println("ID: " + array[i].getId() + " Name: " + array[i].getName() + " Age: " + array[i].getAge());
Employee[] array2 = new SortByName[3];
array2[0] = new SortByName("Gautam", 1222, 20);
array2[1] = new SortByName("Shivam", 1221, 20);
array2[2] = new SortByName("Ankit", 1223, 21);
Arrays.sort(array2);
for (int i = 0; i < array2.length; i++)
System.out.println("ID: " + array2[i].getId() + " Name: " + array2[i].getName() + " Age: " + array2[i].getAge());
}
}
该程序运行良好,我只是想问一下,由于我使用的是参数化版本Comparable
,我应该将引用传递给compareTo
类型SortById
还是SortByName
类型?
即使引用是 type Employee
,代码也可以正常运行,尽管指向它的子类(SortByName
或SortById
)。
隐式演员表是如何发生的?我读过是不可能的,即不可能将超类类型隐式转换为子类。