1

So say we have this player class.

Is it better to do this:

public class Player
{
    public Vector2 position = new Vector2();

    public Player()
    {}
}

or this:

public class Player
{
    public Vector2 position;

    public Player()
    {
        position = new Vector2();
    }
}

Or does it not matter at all? I like doing the first way because the code will be more clear then

Nahro
  • 406
  • 3
  • 12
  • Scope of variable and memory occupies will be affected, doea not affect in small scale project, but yes do have effect on large scale. – MarmiK Aug 20 '15 at 09:06
  • From style perspective, I would go with the second example: if your constructor has a parameter that's assigned to a field, then all field assignments are in one place. – Lyubomyr Shaydariv Aug 20 '15 at 09:20
  • @MarmiK - Why would variable scope or memory footprint be affected? It should be the same for either method. – monkeyhybrid Aug 26 '15 at 19:55

2 Answers2

4

The first way is better if position can be created without reference to any arguments passed into a constructor. Which is true in this particular instance.

It saves you having to duplicate code if you require more than one constructor. Although you can delegate constructors in Java, the first way remains the clearer approach.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Purpose of initializing position inside the constructor is when you need to assign a value to it.

Example

    public class Player
    {
          public Vector2 position;

          public Player(Vector2 pos)
          {
                  position = pos;
          }
    }

Initializing it inside constructor does not make any difference but defies the purpose of doing so.