How to reset current object in Java?

Viewed 56509

If I have an object myObject of type Foo, while inside myObject, is there a way to reset itself and run the constructor again?

I know the following does not work, but might help convey the idea.

this = new Foo();
6 Answers

There is no way to run a constructor again on an existing instance. However, you can organize your code in a way to allow resetting with a minimum amount of work, like this:

public class MyClass {
    public MyClass() {
        reset();
    }
    public void reset() {
        // Setup the instance
        this.field1 = ...
        this.field2 = ...
    }
}

Note: your reset method needs to set all fields, not just the ones that you usually set in the constructor. For example, your constructor can rely upon the default initialization of reference fields to null and numeric fields to zero; your reset method needs to set them all explicitly.

An alternative approach, which is gaining in popularity because it tends to make code easier to reason about, is to make your objects immutable, and instead of changing their state (e.g. resetting them), simply create a new object.

Just write a method that will "reset" all the variables of your object (null or 0 or default value).

Have a set of default values or states for your class stored inside of it. Then write a reset() method that will restore all of these defaults within the class.

public void reset(){
    // Reset everything to your default values
}
Related