Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:

public class Dice

{

    private int topFace = 1;

    private Random myRand = new Random();

    public void Roll()

    {

       // ......

    }

}

or in a constructor?:

public class Dice

{

    private int topFace;

    private Random myRand;

    public Dice()

    {

        topFace = 1;

        myRand = new Random();

    }

    public void Roll()

    {

        // .....

    }

}

I'm really curious about what some of you veterans think is the best practice. I want to be consistent and stick to one approach.

1 Answer

0 votes
by (46k points)

My practices:

  • Don't initialize among the default values in the declaration (null, false, 0, 0.0…).
  • Favor initialization in the declaration if you don't have a constructor parameter that alters the value of the field.
  • If the value of the field turns because of a constructor parameter sets the initialization in the constructors.
  • Be regular in your exercise (the most essential rule).

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...