Page 1 of 1

About Question enthuware.ocpjp.ii.v11.2.3405 :

Posted: Mon Aug 12, 2019 1:25 pm
by BinSlayer
I see 2 reasons why this class is not immutable.

1) The getMaturity method should return a clone of maturityDate. This is indeed the answer highlighted by Enthuware software.

2) I can pass a java.util.Date to the build() method and then I can modify this Date in my own code context. Because the constructor directly assigns a mutable parameter to a mutable field (this.maturityDate = matDate;) . A clone should be made here.

Re: About Question enthuware.ocpjp.ii.v11.2.3405 :

Posted: Tue Aug 13, 2019 12:11 am
by admin
Correct. If that were an option, it should be selected as well.
Added it now.
thank you for your feedback!

Re: About Question enthuware.ocpjp.ii.v11.2.3405 :

Posted: Sat Mar 07, 2020 10:08 am
by FlatPanda
The guidelines also state (Guideline 6-1 / MUTABLE-1) that (emphasis from me):
Immutable classes should not be subclassable. Further, hiding constructors allows more flexibility in instance creation and caching. This means making the constructor private or default access ("package-private"), or being in a package controlled by the package.access security property.
For me, this means that in order to guarantee immutability, the class either:
  • should be final
  • should have only private constructors (this includes having at least one constructor, in order to not have a default constructor)
In this question the class being final is not a required answer, because by having a private constructor with arguments there is no default constructor generated and thus the class is not extensible regardless of being final or not. Is my reasoning correct here?

Re: About Question enthuware.ocpjp.ii.v11.2.3405 :

Posted: Sat Mar 07, 2020 9:59 pm
by admin
Yes, your reasoning is correct. The explanation has now been enhanced to explain this point as well.

thank you for your feedback!