简体   繁体   中英

Can I give a default value like this to avoid null pointer exception?

Can I give variables default values such as this?

public class Laptop {
    // initializing variable to avoid null pointer exception?
    private String owner = "";

    public Laptop(String owner) {
        this.owner = owner;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }
}
private String owner = "";

Doing this is redundant because it's always overwritten in the constructor. The constructor would effectively be this:

public Laptop(String owner) {
    super();
    this.owner = "";
    this.owner = owner;
}

Clearly, the first assignment gets stomped straight away, so there's no point in doing it. Remove the initializer on the field.

If you want to be able to create a Laptop without an owner, you can provide a default value by overloading the constructor:

public Laptop() {
  this("");
}

public Laptop(String owner) {
    this.owner = owner;
}

Now you can invoke like:

Laptop owned = new Laptop("me"); // Will use the explicitly-provided owner "me".
Laptop unowned = new Laptop();   // Will use the default "".

If you never want owner to be null (I presume you're worried about later, when you use the result of getOwner() ), add a null check wherever you assign owner :

this.owner = Objects.requireNonNull(owner);

This will fail with an NPE at the point of assignment, but that's a good place to fail if you never want a null -valued field: you can see exactly where that null came from, and fix that.

You could do something like what Andreas suggested in comments :

this.owner = (owner != null ? owner : "");

but I would recommend against this: if you want owner to be "" , that's the value you should pass into the constructor; passing in null , if that's not an allowed value, should be made clearly incorrect by throwing an exception. Passing in a value and having it coerced to some other value would feel surprising.

Where do you expect a NullPointerException ? None of the code in your sample would cause an NPE, no matter if you initialise the attribute owner with the empty String, or not.

And when you call new Laptop(null) or Laptop.setOwner(null) , the attribute value will be overwritten, no matter which value it had before.


But yes, in general such an initialisation can be used to prevent an NPE, under the proper circumstance. Your code does not provides these circumstances …

What you have done is fine but in order to guarantee that getOwner() will never return null you need to safeguard your set method like:

public void setOwner(String owner) {
    this.owner = owner != null ? owner : "";
}

If on the other hand, setting null should be treated as an Exception because setting this property is considered violation of your workflow:

public void setOwner(String owner) {
    if (owner == null) {
       throw new IllegalArgumentException("Unexpected owner found.");
    }
    this.owner = owner;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM