Do I have to initialize an object with "null" in the constructor, if i do not get it as an argument?

2.1k views Asked by At

enter image description here

Does the constructor for the "Tenant" class have to look like this?

private String name;
private MyDate rentedFrom;
public Tenant(String name)
{
  this.name = name;
}

or this?

private String name;
private MyDate rentedFrom;
public Tenant(String name)
{
  this.name = name;
  this.rentedFrom = null;
}
1

There are 1 answers

5
Cedric On

As long as your variables are not final you don't need to initialize them with null. Though it is bad practice not doing so, this is why I would recommend doing so.

Means this code is the "better" one:

private String name;
private MyDate rentedFrom;

public Tenant(String name) {
    this.name = name;
    this.rentedFrom = null;
}