A normal constructor always returns a new instance of the current class (except when the constructor throws an exception).
A factory constructor is quite similar to a static method with the differences that it
- can only return an instance of the current class or one of its subclasses
- can be invoked with
new
but that is now less relevant sincenew
became optional. - has no initializer list (no
: super()
)
So a factory constructor can be used
- to create instances of subclasses (for example depending on the passed parameter
- to return a cached instance instead of a new one
- to prepare calculated values to forward them as parameters to a normal constructor so that final fields can be initialized with them. This is often used to work around limitations of what can be done in an initializer list of a normal constructor (like error handling).
In your example this code
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : parsedJson ['score']
could be moved to the body of a normal constructor because no final
fields need to be initialized.