gpt4 book ai didi

java - 必须实现抽象方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:35 25 4
gpt4 key购买 nike

这是使用Processing 3.5,并不是每个java东西在这里都一样工作。
Bird 类给我错误,说它需要实现 call()。不是已经在main下面了吗?我对界面没有经验,所以我不知道这里到底发生了什么。

 public interface FuncCall<A> {
A call();
}

class Bird implements FuncCall{
//Error here ^
//The type FuncCallTest.Bird must implement the inherited abstract method FuncCallTest.FuncCall.call()
//Is this not implemented already under main?

float x, y, size;
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();

public Bird(float x, float y, float size){
this.x = x;
this.y = y;
this.size = size;
}

public void main(String[] args){

FuncCall<Float> getX = new FuncCall<Float>(){
@Override
public Float call(){
return x;
}
};

FuncCall<Float> getY = new FuncCall<Float>(){
@Override
public Float call(){
return y;
}
};

FuncCall<Float> getSize = new FuncCall<Float>(){
@Override
public Float call(){
return size;
}
};

inputs.add(getX);
inputs.add(getY);
inputs.add(getSize);

}

}

class Pol {

ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();

public Pol(ArrayList<FuncCall<Float>> inputs){
this.inputs = inputs;
}

//public float call(ArrayList<FuncCall<Float>> arr, int index){
//return arr.get(index).call();
//}
//How do I do this? Do I need to implement the interface here as well? Because if so same error as on Bird

}

我还将把这个额外的部分贴在此处的末尾。System.out.println(pol.call(pol.inputs, 1));
那行得通吗?编译前不会报错。
我很感激任何帮助。请询问是否有些事情没有意义,因为我对堆栈还很陌生,而且对 java 也不是最好的。 :)
主文件:

 void setup(){

Bird bird = new Bird(1.2, 3.2, 7.5);
Pol pol = new Pol(bird.inputs);
System.out.println(pol.call(pol.inputs, 1););
}

最佳答案

首先,您可以跳过 FuncCall 接口(interface)并使用 Java 的Supplier 功能接口(interface),只需将这些Supplier 分别将类对象getter 的方法引用添加到列表中即可。另一种方法是提供一个具有 x、y 和 size 的 getter 和/或成员变量的接口(interface)或抽象类,并使用此接口(interface)或抽象类作为列表的类型参数。

  1. 与供应商:这更接近您的示例,并且需要的更改较少你的代码。带有接口(interface)的第二个选项会更改您的 Pol 类完全如此,我不确定这是否适合您。

´

public class Bird {

private float x;
private float y;
private float size;

public Bird(float x, float y, float size) {
//set your members here
}

public Float getX() {
return this.x;
}

public Float getY() {
return this.y;
}

public Float getSize() {
return this.size;
}
}

´然后是 Pol 类´

public class Pol {

private final List<Supplier<Float>> inputs;

public Pol(List<Supplier<Float>> inputs) {
this.inputs = inputs;
}

public Float call(int index) {
return this.inputs.get(index).get();
}
}

´你的主要应该是这样的´

public static int main(String[] args) {

Bird bird = new Bird(1.0f, 1.0f, 2.5f);

Pol pol = new Pol(Arrays.asList(bird::getX,
bird::getY, bird::getSize));
Float birdsSize = pol.call(2);

return 0;
}

´

关于java - 必须实现抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56028042/

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