Benjiboy50Fonz
Benjiboy50Fonz

Reputation: 23

Do something when a variable is (re)assigned Java

This is a far-fetched question and I am not sure how to approach this problem, so I am open to other workarounds or proposals. As far as I am aware, what I am trying to do is impossible, but I'd like a second input.

Assume we have the following Java code:

int val = 4;

I am curious as to if some sort of function is called when this statement is executed. An overridable function that assigns a given memory location to this value, or something of that nature.

My objective would be to override that function and store this data here and in a file elsewhere as well.

This would need to work for all data types and for reassignments such as that shown below.

val = getNumber(); // Returns 6; 

I would have some sort of direction if I was working with Python, but unfortunately, that is not the case.

My best idea for a solution is to call a function that simply returns a provided argument. Due to the application of this, I'd like to avoid this and keep the usage of this framework as conventional as possible.

Thanks!

Upvotes: 0

Views: 95

Answers (1)

Randika Geekiyanage
Randika Geekiyanage

Reputation: 11

I don't think any kind of function happens when we assign values. However when we assign a value to a primitive type(int, double...) variable the value is stored in the stack memory. If the data is reference type (String...), then it is stored in the heap memory. Only the reference address will be stored in the stack. Whenever you decide to change the state of that particular variable (field value) the new value will be stored in the stack overriding the previous value. So, you don't have to worry about methods to override using a method.

If you want to deny access to a variable outside the class, but still change the state of that variable, then you can use encapsulation concept of OOP in java.

For further clarification refer this article about stack vs. heap

Upvotes: 1

Related Questions