简体   繁体   中英

Writing “reset” method, re-initializing objects not working - Java

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

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.

I changed

public CoolCat(){
    area = LEO_START_AREA;

to

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

and this fixed the problem completely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM