jumar
jumar

Reputation: 5390

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

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

}

Upvotes: 5

Views: 818

Answers (4)

Silfverstrom
Silfverstrom

Reputation: 29348

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

Upvotes: 7

starblue
starblue

Reputation: 56822

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

Upvotes: 1

Peter
Peter

Reputation: 1801

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;
        }
     }
 }

Upvotes: 6

erickson
erickson

Reputation: 269857

Declare bar to be final, like this:

private final Object bar;

Upvotes: 16

Related Questions