给我分配了两个给定的类,一个抽象的父类Lot.java和测试类TestLots.java。我不应该编辑其中任何一个。分配是创建Lot的两个子类,以便TestLots中的错误不再是错误。
该程序的目的是按如下顺序显示批次的名称和区域:
Lot ID L3 has area: 13500.0
Lot ID L2 has area: 27000.0
Lot ID L1 has area: 35000.0
Lot ID L4 has area: 70000.0
但是我得到了错误:
不兼容的类型:LotType1无法转换为Lot,并且
LotType2无法转换为Lot。我怀疑问题出在我的子类中以及应该重写或引用父类的方式。
这是TestLots,出现错误:
public class TestLots {
public static void main(String args[]){
// an array of lots -- some of type1, some of type2
Lot[] lots = {new LotType1("L1",350, 200), // error here
new LotType2("L2",100,270),
new LotType1("L3",100, 270),
new LotType2("L4",350,200)
};
// sort the lots of mixed types by area (note, you'll have to implement
// Comparable interface correctly in LotType1 and LotType2 for this to work:
java.util.Arrays.sort(lots);
// print out sorted results
for (Lot lot: lots) {
System.out.print(lot + " ");
System.out.println();
}
}
}
这是上课,父班
public abstract class Lot {
public abstract double calculateArea();
public abstract String getID();
@Override
public String toString() {
return "Lot ID "+ getID() +" has area: "+ calculateArea();
}
}
子类几乎相同:
public class LotType1 extends Lot implements Comparable<LotType1>{
String name;
int height;
int width;
double area;
public LotType1(String name, int height, int width) {
this.name = name;
this.height = height;
this.width = width;
}
public String getID() {
return name;
}
public double calculateArea() {
return area = ((width * height)/2);
}
@Override
public int compareTo(LotType1 lot) {
area = ((width * height)/2);
if(area==lot.area)
{
return 0;
}
else if(area>lot.area)
{
return 1;
}
else
{
return -1;
}
}
}
编辑以添加LotType2:
public class LotType2 extends Lot implements Comparable<LotType2>{
String name;
int height;
int width;
double area;
public LotType2(String name, int height, int width) {
this.name = name;
this.height = height;
this.width = width;
}
public String getID() {
return name;
}
public double calculateArea() {
return area = (width * height);
}
@Override
public int compareTo(LotType2 lot) {
area = (width * height);
if(area==lot.area)
{
return 0;
}
else if(area>lot.area)
{
return 1;
}
else
{
return -1;
}
}
}
抱歉,这篇文章太长了。我决定包括所有相关文件,以防万一。
最佳答案
问题是您不能在同一集合中对具有不同可比实现的对象进行排序。更改子类以实现Lot的Comparable:
public class LotType1 extends Lot implements Comparable<Lot> {
并在compareTo方法中使用calculateArea():
@Override
public int compareTo(Lot lot) {
if (calculateArea() == lot.calculateArea()) {
return 0;
} else if (calculateArea() > lot.calculateArea()) {
return 1;
} else {
return -1;
}
}