1. Why do I need access control characters
In the last article (【Java Basics Learning Notes 】4 – Formal entry into the World of Java (classes and objects and their memory allocation details)) described the foundation of Java classes and objects, detailed analysis of the class and object memory allocation problem, At the end, we briefly describe how to access the properties and methods of objects in the heap — using variables that hold the address of the object (similar to Pointers).
Greatly improved security
This method of accessing objects directly through variables is extremely insecure, in JavaTo improve the security of the programTo joinAccess control character, so that the object, object methods, object properties have the corresponding permissions, will not be easily accessed.Encapsulate the class
(key)
In object-oriented thinking,Use access control characters to add attributes and methods of a class to permissions that are not accessed by outsiders but provide interfaces (methods that can be called by outsiders).This is calledClass to encapsulate
.
2. Usage of access control characters
- Access control characters precede class definitions, attribute definitions, and method definitions to modify their access permissions. Otherwise, they are default.
- Inside a class, all members can access each other. Access control characters are transparent. Access control characters are external to the class.
3. Four types of access control characters
Access control character | role |
---|---|
private | Private, not allowedAny method outside of this classaccess |
protected | Protected, accessible in the same package, visible to subclasses in different packages |
public | Public, available fromAny placeTo be accessed |
Default (no control character) | Any place in the same package can be accessed, different packages are not allowed to access |
Note: This content involves inheritance and packages, can be understood here, after learning inheritance and packages to continue.
Welcome to subscribe to my wechat official account: “McUlover666”.