-2

For example I have a class

class1:

public class car{
private Color carColor;
public car(Color carColor)
{
    this.carColor = carColor;
}

public void setColor(Color carColor)
{
    this.carColor = carColor;
}
}

class2:

public class car{
    private Color carColor;
    public car(Color carColor)
    {
        setColor(carColor);
    }

    public void setColor(Color carColor)
    {
        this.carColor = carColor;
    }
}

Which Constructor would be the best practice in java coding and why?

  • 3
    Both constructors are semantically the same. Best practice? I would say none, make it as you want. – Luiggi Mendoza Mar 31 '13 at 19:22
  • 5
    I generally try to avoid using non-private methods inside constructor since they can be overriden in derived class and used in `super` constructor instead of original method. – Pshemo Mar 31 '13 at 19:24
  • 1
    Follow java naming convention. – Ajay S Mar 31 '13 at 19:24

4 Answers4

2

The first way is more intuitive and shows up more often. i.e. like so:

public car(Color carColor)
{
    this.carColor = carColor;
}

It is more readable. But both are equal so it's a style issue.

See this too: Should I initialize variable within constructor or outside constructor

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216
2

I'd use the first option, since you can have a validation within setColor().

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

Class1 I suppose. Getter and Setter methods are usually necessary but it is the job of the Constructor to initialize variables of that object.

RyPope
  • 2,645
  • 27
  • 51
1

If I have many calculations that should be done on the variable before setting it, I would do it in a separate method, otherwise, I would choose the first approach.

public car(Color carColor)
{
    setColor(carColor);
}

public void setColor(Color carColor)
{
    Color res;
    //Many calculations
    //..
    //..
    //finally 
    this.carColor = res;
}

But if I only want to set it, I would simple:

public car(Color carColor)
{
    this.carColor = carColor;
}
Maroun
  • 94,125
  • 30
  • 188
  • 241