What is the purpose of access modifiers?

后端 未结 6 2142
-上瘾入骨i
-上瘾入骨i 2020-12-19 03:04

I know this applies to many languages, and not just Java, but that is the language I\'m most familiar with.

I understand what the modifiers do, and how to use them.

6条回答
  •  青春惊慌失措
    2020-12-19 03:56

    To avoid other classes having direct access to internal members of the class.

    This is most useful for avoiding that member variables are mutated in an uncontrolled way (e.g. without proper validation, without notifying listeners, ...).

    Another reason to avoid this is that the internal implementation may change at any time but you don't want to break code that uses it.

    As others have noted, the concept is called Encapsulation.

提交回复
热议问题