gpt4 book ai didi

java - 自定义类: Custom type cannot be converted to other custom type

转载 作者:行者123 更新时间:2023-12-02 12:04:42 29 4
gpt4 key购买 nike

我被分配了两个给定类的作业,一个是抽象父类 Lot.java,另一个是测试类 TestLots.java。我不应该编辑其中任何一个。任务是创建Lot的两个子类,使TestLots中的错误不再是错误。

该程序的目的是按如下顺序显示地 block 的名称和面积:

    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();
}
}
}

这是 Lot,父类

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;
}
}
}

抱歉这篇文章太长了。我决定包含所有相关文件,以防有帮助。

最佳答案

问题是您无法对同一集合中具有不同可比较实现的对象进行排序。更改子类以实现 Comparable of Lot :

    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;
}
}

关于java - 自定义类: Custom type cannot be converted to other custom type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46986109/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com