tags:

views:

207

answers:

5

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

}
+14  A: 

Declare bar to be final, like this:

private final Object bar;
erickson
+6  A: 

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

Silfverstrom
A: 

Shame on me. I need some vacation...

jumar
+5  A: 

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;
        }
     }
 }
Peter
+1, but I think it would be better to throw an exception or use an assert rather than silently assign a new Object().
Jason Day
+1  A: 

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

starblue