Skip to content
Advertisement

How to access the initial value of an initialized object?

I’m learning java at the moment and I’ve got a question about an object that got initialized and got a variable changed during the program execution.

JavaScript

So, I want this code to get the initial value of life that got initialized, but how would I access it?

JavaScript

So, this method is located in the Char class. I’m trying to get it to return a true value when it gets lower than 25%.

JavaScript

Here is the execution program. All the other methods work just fine, but as pointed out, it’ll never return true because it can’t be a quarter of itself. Don’t mind the prints, I’m just testing it.

Advertisement

Answer

To do this, you need to create a second variable that stores the value passed into the constructor:

JavaScript

As you can see, I store the initial life and I don’t ever modify it. Since I modify the life variable, I can’t use it to keep track of the initial value. Modifying a variable is a destructive process, and Java doesn’t have a way to keep track of the history of variable values (unless you do it yourself as shown above).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement