Valid settings of the Java domain accessors

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.