Constructors
Last updated
Was this helpful?
Last updated
Was this helpful?
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/
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
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.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.
Having many constructors, with different parameter list
Allows for default certain fields or parameters
explicit constructor invocation
Using this
in telescoping constructors (see overloading)
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 ?????
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/
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
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
https://www.javatpoint.com/java-constructor
Due to Most DI using reflection, factories might not be possible, and constructors might need to be polluted with logic