0
Java final question
public class Test { private final MyObject myObject = new MyObject(1); public void eineMethode() { myObject = new MyObject(1); //why does this give me an Error myObject.setNumber(2); //but this works? } }
4 ответов
+ 3
There is difference between modifying the object and modifying the state of an object.
Take this for reference.
https://code.sololearn.com/cFrusM41sVFy/?ref=app
+ 3
So you create a field which holds an instance of Myobject this instance is final which means you cannot reassign it.
Then you have a method which tries to assign a new instance to a final variable myObject, this will result in an error as it already exists and cannot be reasigned..
myObject.setNumber(2) would work ok because theres an instance previously created using the final variable field.
0
You set 'muObject' object as final so you can't change its value. So that's why error. Remove final will works..
Edit:
2nd part you are using already defined object not redefining..
For final : You can create and assign value once only, then you can use it any number of times.. That's what you doing with 2nd part.. In 1sr part you are trying to assign new value which is error for final variables....
0
But why does the 2nd part work?