Final objects

One thing i’ve noticed when you declare an instance of an object as final,
is that you can still modify the object properties, even while the object is declared as final.

Example:

// Final object example
final Foo myFoo = new Foo();

//This will output the default value, let's say 0
System.out.println(myFoo.getValue());

// Set the value to 20
myFoo.setValue(20);

//This will output the new value, 20, with no compilation errors
System.out.println(myFoo.getValue()); 

One thing you’ll have to keep in mind is that when you’d like to re-declare the object:

// Re-declare the object
myFoo = new Foo();

This won’t work, it’ll throw errors since myFoo was final after all 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.