2

I am working on a generic implementation of the Genetic Algorithm. I'm trying to extend a specific Individual for the knapsack problem from the abstract class Individual

package GenericGA;

public abstract class Individual {

    private double fitness;
    private double probability;


    public double getFitness() {
        return fitness;
    }

    public double getProbability() {
        return probability;
    }

    public void updateProb(double totalFitness){
        probability = fitness/totalFitness;
    }


    abstract void updateFitness();
    abstract Individual crossover(Individual partner);
    abstract void mutate(double mutationRate);

}

This is the extended class

package GenericGA.SpecificImplementations;


import GenericGA.Individual;

public class KnapsackIndividual extends Individual {


    void updateFitness(){

    }

    Individual crossover(Individual partner){
        return null;
    }

    void mutate(double mutationRate){

    }

    public static void main(String[] args){
        System.out.println("Hello");
    }

}

Since I was using intellij and it was giving me the error, I thought that could be a problem of the IDE, so I compiled with javac and I get the same error:

GenericGA.SpecificImplementations.KnapsackIndividual is not abstract and does not override abstract method mutate(double) in GenericGA.Individual

There are no spelling mistakes and the signatures are correct, and I get the error also for the other abstract methods when removing the mutate method that is giving the error.

Moreover if I use @Override on top of the methods, it says

Method does not override method from its superclass

What am I missing here?

Thanks in advance.

GioGio
  • 448
  • 2
  • 5
  • 22
  • 2
    Your implementation class cannot override package-private abstract methods in `Individual`, because it is in a different package. – khelwood Jun 11 '18 at 11:39

2 Answers2

3

It looks like your abstract mutate method is not visible to the sub-class, since it has default access (which is package private), and the KnapsackIndividual sub-class is in a different package.

Change the abstract method to:

protected abstract void mutate(double mutationRate);

and change the overriding method accordingly:

@Override
protected void mutate(double mutationRate){

}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

A concrete(non abstract) class must implement all non implemented (abstract) methods inherited from the parent class. You are implementing the same methods, but since they are private to the class they are not visible, and hence it is as if they are not implemented.

NiVeR
  • 9,644
  • 4
  • 30
  • 35