I am looking for a clean and safe way to ensure tha a field of a class will never be set to null. I would like the field value to be set once in the class constructor and never modified later. I think that he readonly keyword in C# allows this. Is there a way to do the same in Java?
class foo
{
private Object bar;
public foo(Object pBar)
{
if(pBar == null)
{
bar = new Object();
}
else
{
bar = pBar
}
}
// I DO NOT WANT ANYONE TO MODIFY THE VALUE OF bar OUT OF THE CONSTRUCTOR
}
Declare bar
to be final
, like this:
private final Object bar;
You're looking for the keyword final.
class foo
{
private final Object bar;
public foo(Object pBar)
{
//Error check so that pBar is not null
//If it's not, set bar to pBar
bar = pBar;
}
}
Now bar can't be changed
Both the previous answers are correct, but pBar could still be set to null:
new foo(null);
So the ultimate answer is to use the final keyword and make sure pBar isn't null (as before):
public class Foo
{
private final Object bar;
public Foo(Object pBar)
{
if (pBar == null)
{
bar = new Object();
}else{
bar = pBar;
}
}
}
You want to declare the field as final, e.g.
private final Object foo;
This has the added benefit that w.r.t. concurrency the field is guaranteed to be initialized after the constructor has finished.
Note that this only prevents replacing the object by another. It doesn't prevent modifications to the object by methods of the object, e.g. setters, unlike const in C/C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With