[SOLVED] Difference between static vs non-static variables explained (With Images)

Static variables can be a little confusing to explain through text. So if you are a visual learner like me, here is an example of how static variables work, compared to non-static variables:

HOW STATIC VARIABLES WORK:

Lets say this is the starting state of the bricks and the brick class.

Lets say Brick 2 adds + 1 to the breakableCount

Then breakableCount updates in every brick AND the original class / template it was created from.

Now lets say that Brick 4 also adds +1 to breakableCount. It will update again everywhere.

It doesn’t have to be a Brick that updates breakableCount. Other Classes can update breakableCount by updating it direclty in the Class(Brick).

breakableCount will update in all locations still, even though we are editing the Class(Bricks), all the bricks themselves will also be updated!

3 Likes

HOW NON-STATIC VARIABLES WORK

Lets start the same way we started before with breakableCount = 0 everywhere:

Lets say that Brick 2 adds +1 to breakableCount.

Brick 2 will only update its OWN breakableCount. Everywhere else will remain 0.

Lets say Brick 4 updates breakableCount. It will only update its OWN breakableCount.

Since the bricks can each have different values, and they only update themselves, the value of breakableCount is not the same in every brick anymore. SO we can not read from the Class (Brick) to get the value of breakableCount, because it will be different in each brick. This is why we can not access the variable breakableCount from the Class (Brick) when the variable is NON-STATIC. However, we can read/write to breakableCount in each individual brick. We just can not read/write to breakableCount in the Class(Brick) since each brick holds its own value.

2 Likes

NOTE
If you research this topic, you will come across very advanced terms like pointers, referencing, and memory allocation. These are very high end programming concepts and will be very confusing to new programmers. You do not need to know about these concepts to use a static variable. But if you see these terms just be aware that they are talking about very advanced topics. All you really have to understand is the above and you should be fine.

There is one other basic functionally that static variables have, which is that they also hold their values between method execution cycles. This has not been discussed yet in the course, but just be aware that this is something else a static variable can do.

1 Like

Privacy & Terms