During encapsulation, You need to obtain or set the value of the Instance domain. The following three items should be provided:
1. A private data domain
2. A public domain accessor method
3. A public domain modifier Method
Java core programming has mentioned such an improvement for encapsulation:
PublicDomain accessors,For example:
Public date getgatherdate () <br/>{< br/> return gatherdate; <br/>}
Suggestion: Do not write the accessor method that returns the referenced variable object, because this will destroy the encapsulation.
For example:
Employee Harry = ...; </P> <p> date d = Harry. gethireday (); </P> <p> double tyms = 10*2345*4567*4568; </P> <p> D. settime (D. gettime ()-(long) tyms); <br/>
The cause of the error is subtle, but it is indeed Unforgettable! Because d and Harry. hireday reference the same object, we actually return the reference of this variable object. What we need is a copy of the object in another location, not the reference of the original object! At this time, it is OK to clone the original object.
Public date getgatherdate () <br/>{< br/> return (date) gatherdate. Clone (); <br/>}
PS: if a copy of a variable data domain is returned, the clone function should be used.