I'm deriving a class, let's call it JCustomPanel
, from the JPanel
class. Several basic properties need to be initiliazed, such as opacity, background color, various listeners, and so on. How should this initialization be done correctly?
The most obvious idea is to do it in the constructor of JCustomPanel
. However, all the methods to manipulate these properties (such as setBackgroundColor
or addComponentListener
) are overridable, and my IDE complains (rightly so, I assume) that overridable methods should not be called in the constructor.
Another option is to define an init
method in my JCustomPanel
that does all of this work, and then manually call this whenever I create a new JCustomPanel
. But this is annoying, and one would be prone to forget to call init
, which would introduce errors.
So what's the best practice here?
By the way, I looked at the source code of JList
, and it calls setOpaque
in its constructor (see here).