Reputation: 49
I have some calculation made in the constructor of a class and now let assume I want to change one of the variable field in this class, which will affect the calculation that have been made before.
For each time I will call any set
method
I will need to run again the calculation
(or copy the code twice (which is bad coding..))
I think the code will look better if I could do like as shown below, I just want to know what is the reason it can't be done?
class Entity
{
private int x,y,z;
public Entity(int x,int y,int z)
{
Calculating();
}
private void Calculating()
{
// ...
}
public void Set_X(int x)
{
this = new Entity(x,this.y,this.z)
}
}
Upvotes: 0
Views: 88
Reputation: 843
You cannot assign a new object to this
. This always references the current object.
Why don't you just set X and invoke the Calculting()
method from Set_X
? This will change the current object's state.
If you do not want to change the current object, e.g. because of other references to it, you will have to create a new instance and return it from Set_X
.
Upvotes: 4