Access modifiers in Java for set access levels for classes, variables, methods and constructors. These are the access levels:
- Visible to the world, Everyone can see it. (public).
- Visible to the package and all subclasses (protected).
- Visible to the package. the default. No modifiers are needed. (Package Private/No modifiers)
- Visible to the class only (private).
Access levels affect you in two ways. First, when you use classes that come from another source, such as the classes in the Java platform, access levels determine which members of those classes your own classes can use. Second, when you write a class, you need to decide what access level every member variable and every method in your class should have.
Remarks for programming
Suggest rule:
Start with declaring everything private. And then progress towards public as the needs arises and design warrants it, use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.
This article is a collection of information in internet, reference from the links provided:
Reference:
No comments :
Post a Comment