Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure that a field will never be null in a Java class

Tags:

java

null

field

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

}
like image 283
jumar Avatar asked Jun 09 '09 14:06

jumar


4 Answers

Declare bar to be final, like this:

private final Object bar;
like image 86
erickson Avatar answered Oct 17 '22 03:10

erickson


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

like image 28
Silfverstrom Avatar answered Oct 17 '22 02:10

Silfverstrom


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;
        }
     }
 }
like image 6
Peter Avatar answered Oct 17 '22 02:10

Peter


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++.

like image 1
starblue Avatar answered Oct 17 '22 02:10

starblue