-1

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;
}
Jens
  • 67,715
  • 15
  • 98
  • 113
  • 1
    No you must not initialize objects with null it will be done automatically – Jens Jan 11 '20 at 17:38
  • What kind of diagram is this anyway? I've never seen a variable defined above the relation. – maio290 Jan 11 '20 at 17:40
  • @maio290 seems like pretty standard UML, apart from the relation looking like a mix of composition and association. – Fureeish Jan 11 '20 at 17:42

1 Answers1

0

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;
}
Cedric
  • 408
  • 1
  • 4
  • 18
  • "*Though it is bad practice not doing so*" - then why not initialise them as you declare them? Instead of having `this.rentedFrom = null;` inside the constructor, change the declaration to `private MyDate rentedFrom = null;`. – Fureeish Jan 11 '20 at 17:40
  • 1
    Because usually this is considered to be not that elegant as well... Yeah it is possible though declaring them as ‘null‘ outside of the constructor is kind of unnecessary because a.) They will be overridden anyways by the constructor in many cases and b.) They are ‘null‘ to begin with... – Cedric Jan 11 '20 at 17:45
  • "*Because usually this is considered to be not that elegant as well...*" - why is that? Who claims so? Reliable sources needed. "*They will be overridden anyways by the constructor in many cases*" - this does not invalidate initialization to uniform, default value. "*They are ’null’ to begin with...*" - then why assign `null` to them inside the constructor and do **more work** than just initialising them alongside declaration? – Fureeish Jan 11 '20 at 17:49
  • Maybe sounds like a lame excuse but apart from having seen this in most professional APIs and so on this is also the way it was taught at my university and school. – Cedric Jan 11 '20 at 18:13
  • Then please link the sources of those professional APIs. Unfortunately, univiersities often disagree about what's a good practice. – Fureeish Jan 11 '20 at 18:15