Reputation:
I'm aware that you could call a method from a constructor, but it could lead to problems later on if the method could be overridden. The following code is just an example I've written demonstrating my issue:
Let say I have the following subclass:
private boolean isActive;
public ChargeGun(String gameObjectID, String gameObjectName, String desc, int numberofshots, int damage, boolean isActive) {
super(gameObjectID, gameObjectName, desc, numberofshots, damage);
setAttributes(isActive);
}
public ChargeGun(String gameObjectID, String gameObjectName, int numberofshots, int damage, boolean isActive) {
super(gameObjectID, gameObjectName, numberofshots, damage);
setAttributes(isActive);
}
private final void setAttributes(boolean isActive)
{
this.isActive = isActive;
}
The boolean isActive
is specific to ChargeGun
and not any other gun. Given that I have two constructors in my subclass, rather than type isActive = true
twice, could I call a private final method
to do it? The reason is, if my attributes for ChargeGun grow, then I would have to add attributes in both constructors. If I do it with a private final method, everything is set in one place. Is this bad practice?
I can't chain the ChargeGun constructors because both call the super classes constructor.
Upvotes: 1
Views: 71
Reputation: 1720
If you need your setAttributes, it certainly means you have common variables to always set the same way in multiple constructors. Wouldn't it be more clear to have a "full constructor" which have all the assignment you make in setAttributes, and other shorter versions of your version calling the full version ?
Also, you really should consider using Builder pattern which clearly deals with those object that can be constructed in many different ways. If you thing it is a lot of work, just know that some plugins for IDE such as InnerBuilder make it easy to generate. If you look at how languages evolve, you will see more and more builder-like api (Stream, Optional...).
Upvotes: 0
Reputation: 201537
A private
method cannot be overriden, you do not also need to mark it final
(which also means it cannot be overriden). Just one of final
or private
would be sufficient. However, the method needs to be modified slightly. Like,
private void setAttributes(boolean isActive)
{
this.isActive = isActive;
}
your version always sets it to true
. If that is intentional I would remove the setter entirely, and do something like
private final boolean isActive = true;
which is a declaration and initialization of an immutable field.
Upvotes: 5