Should I use getters and setters in constructors?

You should not call getters and setters from the constructor.

A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will.

The only way to guarantee initialising the fields is to assign them. If you call a setter there is a chance it could be overridden and it might do something else. It might call a method in sub-class which is not initialised yet.

Calling a getter is also a bad idea if you are just getting a field from the same class. If it has been declared in the super-class you might justify it; if you need to get data from the super-class in the sub-class, you will have to call the getter (unless it is protected). If you need to communicate data from a sub-class to the super-class during construction you should pass it as a parameter. But this is a different use-case to what you are describing and the sub-class would probably not have your own field corresponding to the getter anyway.

If you have any "special" initialisation code, put that in a separate private method and call it from both the constructor and the setter separately.


It depends, do you plan on ever subclassing this class, should someone else be able to subclass your class?

  • If the answer is no then, you could use it, but I would say it's generally bad practice to do so for several reason, if you don't explicitly forbid inheritance then the class can be subclassed and the methods overridden see quote below. In general it's good practice to aim for as much immutability as you can and using getters/setters keeps you from doing that. I would also argue that Constructors should only have parameters that are necessary to initialize a class to a valid state. If they can be also passed in using setters then they might not be necessary for a valid state to be achieved.
  • If you want to design your class with inheritance in mind then the answer is no and if you use init method it can't use getters/setters either, or any method that can be overriden. Direct quote from Effective Java 2nd Edition:

There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will get invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.

Tags:

Java