What is the purpose of access modifiers?

后端 未结 6 2134
-上瘾入骨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 04:01

    More or less they are used to control who can access your member variables and functions. It's the broader concept of encapsulation at work in Java(http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)).

    From the Oracle Docs:

    Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:

    At the top level—public, or package-private (no explicit modifier).

    At the member level—public, private, protected, or package-private (no explicit modifier).

    http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    As to why you should do this:

    It has to do with intent of use. It would probably be best described as a design choice that helps guide usage through-out the code-base. By marking something private you are telling other developers that this field or method should not be used outside it's current purpose. It really becomes important on large projects that shuffle developers over time. It helps communicate the purpose & intended uses of classes.

提交回复
热议问题