Java final question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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? } }

19th Oct 2020, 3:07 PM
Manfred h
4 Answers
+ 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
19th Oct 2020, 4:12 PM
Avinesh
Avinesh - avatar
+ 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.
19th Oct 2020, 4:08 PM
D_Stark
D_Stark - avatar
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....
19th Oct 2020, 3:31 PM
Jayakrishna 🇮🇳
0
But why does the 2nd part work?
19th Oct 2020, 3:56 PM
Manfred h