Writing "reset" method, re-initializing objects not working - Java

703 Views Asked by At

I have attempted to create a reset method by "re-initializing" the objects in question to new objects. What is happening is that some of the values stored in the objects are being reset, as per the constructors, yet some are not. Can anyone explain this?

  public void reset(){
    if(gameHasEnded){
      dicaprio = new CoolCat();
    }  
  }

above is an example of my reset method to reset the object below:

 public CoolCat(){
    area = LEO_START_AREA;  //rectangle object

    speed = 2 + (int)(5*Math.random());

    direction = RIGHT;     
  }
  • direction and speed appear to get reset but the area does not
2

There are 2 best solutions below

0
On

If you're using concurrency, then the first question to ask if its your reset method atomic (synchronized on some lock? or on this object, using default synchronized method modifier)? If its a simple singlethreaded program, then are you sure you are "resetting" the instance variable of your object to new objects themselves (if theyre not primitives that is), and not existing ones? Last but not least, in your reset just try setting the values to null (yourObjToRest=null;) before reinitializing them.

Edit: some code would be helpful to give a more specific answer.

0
On

I changed

public CoolCat(){
    area = LEO_START_AREA;

to

 public CoolCat(){
    area = new Rectangle(LEO_START_AREA); 

and this fixed the problem completely.