Instance variables are the same for each object initialization.

I am making a genetic algorithm that develops an array charin "Hello World". The problem is that whenever I initialize an object Chromosomeand call a method generateChromosome, all the chromosomes of the “test” population remain the same?

public class Chromosome{
   private static int defaultLength = 11;
   private static char []genes = new char[defaultLength]; <--- this remains the same for each object :/


   //Generates a random char chromosome
   public void generateChromosome(){
      char []newGene =  new char[defaultLength];
      for(int x = 0; x<size(); x++){
         char gene = (char)(32+Math.round(96*Math.random()));
         newGene[x] = gene;

      }
      genes = newGene;

   }

   //Returns a specific gene in the chromosome
   public char getGene(int index){
     return genes[index];
   }

   public char[] getChromosome(){
      return genes;
   }

   public void setGene(char value, int index){

   genes[index] = value;

   }

   public static  void setDefaultLength(int amount){
      defaultLength = amount;
   }

   public static int getDefaultLength(){
      return defaultLength;
   }

   public int size(){
      return genes.length;
   }

   @Override
   public String toString(){
      String geneString = "";
      for(int x= 0; x<genes.length; x++){
         geneString += genes[x];
      }
      return geneString;
   }
}
+4
source share
5 answers

staticmeans one for each class (not one instance). Removestatic

private char[] genes = new char[defaultLength];

and yours geneswill become the instance field.

+2
source

This is because your variables static, i.e. class variables. They will be the same in every instance of your class.

, static.

+3

static - . genes , static:

public class Chromosome{
   private static int defaultLength = 11; // should probably be final, BTW
   private char[] genes = new char[defaultLength]; // not static!
+2

static , . , , .

static .

+1

genes , static. ,

1) static

2) instance

For more information about static, see fooobar.com/questions/20491 / ...

+1
source

Source: https://habr.com/ru/post/1569262/