Why set getter and setter?

Source: Internet
Author: User

In object-oriented language, attributes are usually set to private, and then the getter and setter methods are added for access. Some people say that this is essentially different from setting an attribute as public. Simply calculate the attribute as public. Some people have refuted this and destroyed the encapsulation. But what are the disadvantages of destroying encapsulation?

When I was reading a handout on C ++ at Stanford University today, I saw the following statement about this question:

Class involves two roles: implementer and client. The implementer is responsible for implementation and provides interfaces. The client is responsible for calling interfaces, but does not care about implementation. If the attribute becomes public, it is exposed to the client, and the client calls the public attribute. If the implementer modifies the internal implementation of the class, such as deleting a public attribute or changing the name (which is reasonable for the implementer), the client will suffer, code that calls public attributes cannot be compiled. Therefore, the internal architecture should be isolated from the client.

Why set getter and setter?

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.