我正在使用 ECJ(一种进化算法包),我想调用扩展类中的某些变量,但我不知道如何从问题类中获取它们。
正如您在下面的问题类中看到的,我希望能够在 NetworkGene 类中调用变量 x,但它不起作用,因为我最终进入了 VectorGene 类,在该类中我只能调用变量 y。
class Problem {
double fitness = 0;
public void evaluate(final Individual ind){
if(!(ind. instanceOf GeneVectorIndividual)){
state.output.fatal("Not a GeneVectorIndividual",null);
}
fitness = 0;
for(){
fitness += ind.genome[i].x;
}
}
}
public abstrabct class VectorIndividual extends Individual{
}
public class GeneVectorIndividual extends VectorIndividual{
VectorGene[] genome;
}
public abstract class VectorGene implements Prototype {
double y;
}
public class NetworkGene extends VectorGene{
double x;
}
最佳答案
经典的多态性问题。
快速但肮脏的解决方案是这样的:在 Problem
类的 for
循环中,添加这些行
if (ind.genome[i] instanceof NetworkGene) {
fitness += ((NetworkGene) ind.genome[i]).x;
}
但您可能需要解决一个设计问题:
为什么ind.genome
是一个VectorGenes数组而不是NetworkGenes数组?
x
代表什么?您是否可以在 VectorGene
中表达某种方法,例如 getSomeValue()
方法,在 NetworkGene
中您可以实现该方法以返回 x
> (并且在其他子类中,您将实现它以返回一些其他适当的值)?
您真的需要 VectorGene
和 NetworkGene
之间的继承关系吗?它与您实际需要在您目前正在尝试解决的问题?难道不能只有一个包含属性 x
和 y
的类吗?
关于java - 在 ECJ 中调用父级中的扩展类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9824138/