Alternatives to using overridden methods in constructors, Java


In a Java project I am coding I have ended up using methods that are overridden in constructors. Something like:

class SuperClass { SuperClass() { intialise(); } protected void initialise() { //Do some stuff common to all subclasses methodA(); methodB(); } protected abstract void methodA(); protected abstract void methodB(); } class SubClass1() { SubClass() { super(); } protected void methodA() { //Do something } protected void methodB() { //Do something } } class SubClass2() { SubClass() { super(); } protected void methodA() { //Do something else } protected void methodB() { //Do something else} }

I now realise, that although in my case it works fine, it is somewhat dangerous since SubClass methods are called on an object that has currently only been constructed as a SuperClass object (something that may be overlooked when new classes that extend SuperClass are added in the future). It also wouldn't work in c++ due to differences in how objects are created.

The only way I can think to get round this is to move the initialise method call down to the concrete classes constructor:

class SuperClass { SuperClass() { } protected void initialise() { methodA(); methodB(); } protected abstract void methodA(); protected abstract void methodB(); } class SubClass1() { SubClass() { super(); initialise(); } protected void methodA() { //Do something } protected void methodB() { //Do something } }...

Is this the common way to over come this issue? It seems a shame (and easy to forget) that all further classes that extend SuperClass need to remember to call initialise().

I also found myself doing something similar in a more complicated situational that uses a Factory Method in a constructor, which is overridden in subclasses to decide which concrete class to implement. The only other way I can think to get round this and keep the design pattern as is, is to perhaps construct in a two phase process; i.e. construct with the bare minimum, and then call a second method to finish off the job.


This is really not a good idea as your Subclass will not be properly constructed when its methodA() and methodB() are called. That would be very confusing for people extending the class. Recommend you use an abstract init() instead, as suggested by dlev in his/her comment.


Objects that need initialization as complex as this would really need to be created through factory methods. You do mention a factory, but being called from a constructor, so that doesn't sound like the straightforward approach, either. If you simply had a factory in the base class, publicly invisible constructors, and a mechanism to decide which concrete class to return, that factory would easily enforce the initialization policy.


I wonder if you're making things more complicated than they need to be.

In your example, the stuff done by each implementation of methodA could be moved to the constructor of the class that does the implementation. So instead of using SubClass::methodA, just move the logic into the SubClass constructor.

If you do this you gain clarity at the expense of some potentially hard to understand control over the order the various initialization bits get executed.


What Bruce Eckel suggests in his "Thinking in Java" is making your methodA() and method B() of the class SuperClass final or private (which is implicitly final) so they will be accessible from the superclass constructor though no derived class will have access to these methods and, thus, no dangerous overriding will be possible - any mehtods with similar signature declared in any derived classes will be simply new methods.


  • CLang 3.5 LibTooling: getting file name of a variable in clang::VarDecl
  • How to make Java compiler generate line numbers in compiled code
  • Testing Rails module without loading ActiveRecord
  • Performance difference between accessing local and class member variables
  • How can I compose a WCF contract out of multiple interfaces?
  • PhpStorm: annotation for inherited method return type?
  • What is this strange character in chrome's resource css viewer?
  • Is there any way to call saveCurrentTurnWithMatchData without sending a push notification?
  • Scala: Function returning an unknown type
  • Xaml, wpf image position and crop issue
  • LiveData is abstract android
  • unable to get jsonEncode in magento2
  • Angular2 - Template reference inside NgSwitch
  • C#: Import/Export Settings into/from a File
  • Tell Git to stop prompting me for conflicts when none really exist?
  • Why use database factory in asp.net mvc?
  • Can someone please explain to me in the most layman terms how to use EventArgs?
  • Spring boot 2.0.0.M4 required a bean named 'entityManagerFactory' that could not be found
  • Not able to aggregate on nested fields in elasticsearch
  • How can I set a binding to a Combox in a UserControl?
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • Debug.DrawLine not showing in the GameView
  • Create DicomImage from scratch using Dcmtk
  • Sencha Touch 2.0 Controller refs attribute not working?
  • How to rebase a series of branches?
  • CSS Linear-gradient formatting issue accross different browsers
  • Spring security and special characters
  • Incrementing object id automatically JS constructor (static method and variable)
  • Trying to switch camera back to front but getting exception
  • Statically linking a C++ library to a C# process using CLI or any other way
  • python regex in pyparsing
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Change div Background jquery
  • How does Linux kernel interrupt the application?
  • unknown Exception android
  • Programmatically clearing map cache
  • Busy indicator not showing up in wpf window [duplicate]
  • Python/Django TangoWithDjango Models and Databases
  • Why do underscore prefixed variables exist?