在ECJ中调用父类中的扩展类变量

时间:2012-03-22 14:18:54

标签: java variables parent-child extends

我正在使用ECJ(进化算法包),我想调用扩展类中的某些变量,但我无法弄清楚如何从问题类中找到它们。

正如您在下面的问题类中所看到的,我希望能够在NetworkGene类中调用变量x,但它不起作用,因为我最终在VectorGene类中,我只能调用变量y。< / p>

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

1 个答案:

答案 0 :(得分:1)

经典多态问题。

快速而肮脏的解决方案就是:在班级for的{​​{1}}循环中添加这些行

Problem

但可能你需要解决一个设计问题:

为什么if (ind.genome[i] instanceof NetworkGene) { fitness += ((NetworkGene) ind.genome[i]).x; } 是一个VectorGenes数组而不是NetworkGenes?

ind.genome代表什么?你可以在x中像VectorGene那样表达一些方法getSomeValue(),你可以在NetworkGene中实现返回x(在其他子类中,你实现它以返回一些其他合适的价值)?

你真的需要 VectorGeneNetworkGene之间的继承关系 - 它是否与您目前正在尝试的问题中实际需要利用的某些差异有关解决?你能不能只有一个包含属性xy

的类
相关问题