Recently, read the Sun Weichen teacher's "Java Object-oriented programming" a book, the heart quite a bit of sentiment, thinking to record it down.
Modifiers in Java
In the Java language, there are some words (more accurately, it should be adjectives): abstract (abstract), static, public (common), protected (protected), private (private), Synchronized (synchronous), native (local), transient (transient), volatile (volatile), and final (immutable), which are modifiers that can decorate classes, variables, and methods. The flexibility and proper use of these modifiers will enable our software programs to more closely simulate real-world systems and help improve the reusability, maintainability, scalability, and operational performance of the software system.
Scope of modifiers in Java
- Abstract: Class, member method
- Static: Member method, member variable
- Public: Class, member method, constructor method, member variable
- Protected: Member methods, constructor methods, member variables
- Private: Member method, constructor method, member variable
- Synchronized: Member method
- Native: Member Method
- Transient: Member variable
- Volatile: Member Variable
- Final: Class, member method, member variable, local variable
The classes mentioned above are limited to the top level class, not the inner class (the class defined in the class or method). As you can see from the range of scopes listed above, local variables can be only final decorated, and modifiers for the top-level class include: abstract, public, and final,static, protected, and private cannot decorate the top-level class.
Access Control modifiers
One of the basic ideas of object-oriented is to encapsulate implementation details and expose interfaces. The Java language uses access control modifiers to control classes and access to the methods and variables of the class, exposing the interface only to the consumer, but hiding the implementation details. There are 4 levels of access control:
- Public level: With public decoration, open to the outside.
- Protected level: decorated with protected and exposed to subclasses and classes in the same package.
- Default level: No access modifiers are exposed to classes in the same package.
- Private level: Decorated with private, only the class itself can be accessed, not public.
Access levels apply only to members of classes and classes, not to local variables. Local variables can only be accessed inside a method and cannot be decorated with private, protected, or public
Modifiers in the Java language for Java object-oriented programming