Constructors

What

  • It is a public method, with same name and case as the class. It is invoke when newing up an instance of the class.

  • Constructors should do one thing, just set the fields of the object to the arguments passed in via the constructor

  • https://www.bruceeckel.com/2017/01/13/constructors-are-not-thread-safe/

Default/hidden constructor

  • a constructor that is created by the java if none is provided.

  • Can provide one but it will be there at compile time

  • https://stackoverflow.com/questions/4488716/java-default-constructor

Paramatised constructor

  • A constructor that has parameters

    • Noramlly set age to some field in the class.

  • Parameters are generally set to fields of the objects

  • Parameters are normally the dependencies of the object, and used with in the instance methods to delegate behaviour to them.

    this

    • this.age refers to the object's field, where age is what is pass in to the method via arguments.

    • this on its own refers to the object, thus calling this.run() means calling the objects own run() method which will use its own instnace fields

      • we dont need to use this.run(), when call another method within an class, which just call run(), as it is implicit implied.

Overlaoding

  • Having many constructors, with different parameter list

  • Allows for default certain fields or parameters

  • explicit constructor invocation

  • Using this in telescoping constructors (see overloading)

Private constructors

  • Used for not allow other objects to instantiate an object, only class can do this.

  • Used in general for static factory methods (see below)

  • exanple ?????

Telescoping

  • lots of constructors, as there are lots of fields and want defaults for different versions of the class

  • Use of builder pattern or static factory method

  • https://www.vojtechruzicka.com/avoid-telescoping-constructor-pattern/

Static initialization/ static factory methods

  • Useful for creating new domain objects

  • Useful for adding code (ie validation), setting fields as null or defaults

  • Better naming

  • example

  • https://stackoverflow.com/questions/929021/what-are-static-factory-methods

  • Negatives

    • no inheritance

initialization Block

  • https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

  • https://www.javatpoint.com/java-constructor

Dealing with Dependency injection frameworks

  • Due to Most DI using reflection, factories might not be possible, and constructors might need to be polluted with logic

Last updated

Was this helpful?