Detailed explanation of Java scope and access modifiers
In Java,Scope(Scope) refers to the accessibility and life cycle of variables, methods, or classes, that is, their visible range in code. Scope byThe location of the declarationandModifierJoint decision。
1. The scope of variables
There are five scope types for variables
Scope Type | Declare location | life cycle | Access scope |
Instance variables | Inside the class, outside the method | Object creation to destruction | All non-static methods in the class |
Static variables | Inside the class, outside the method + static | Class loading to the end of the program | All methods in the class, other classes pass the class name |
Local variables | Method/Construction Method/In-block | During method/block execution | The declaration is at the end of the method/block |
Block variables | Inside the code block | During block execution | Inside the block |
Method parameters | Method parameter list | During method call | The whole method body |
2. The scope of the method
Method Type | Accessible members | Call method | Modifier limit |
Example method | Instance variables, static variables, other instances/static variables | Object name.Method name() | No special restrictions |
Static method | Static variables, other static variables | Class name. Method name() or object name. Method name() | Cannot directly access instance members |
Access Modifiers:
It is used to control the visibility and access scope of classes, variables, methods and constructors. It is the core mechanism of Encapsulation in object-oriented programming.
Java provides four access modifiers:
According to the access range, from wide to narrow:public
> protected
> Default (no modifier) > private
Modifier | Visibility range | Typical uses |
public | Globally visible | External interfaces, tool classes, constants |
protected | Same package, word category | Protected methods or variables that allow subclasses to extend |
default | Same pack | Implementation details of in-package sharing |
private | Current class only | Hide internal state, force access through method |
Things to note:
1. When the subclass rewrites the parent class method,Access permissions cannot be smaller than parent class scope
2. When the construction method is modified with private, it is one of the requirements of the singleton pattern, that is, external instantiation is not allowed.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.