简体   繁体   中英

What is the right way to initialize objects?

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

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.

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.

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