There are four types of java access control modifiers, namely public, protected, private, and default access modifiers. Detailed introduction: 1. Public, public is the loosest access control modifier. Modified classes, methods and variables can be accessed by any other class. When a class, method or variable is declared as public, they can be accessed anywhere be accessed, whether it is a class in the same package or a class in a different package; 2. protected modifier, etc.
Java is an object-oriented programming language with rich access control modifiers for controlling access to classes, methods, and variables. In Java, there are four access control modifiers, namely public, protected, private and default access modifiers.
1. public: public is the loosest access control modifier. Modified classes, methods and variables can be accessed by any other class. When a class, method or variable is declared public, they can be accessed from anywhere, whether it is a class in the same package or a class in a different package. For example:
java public class MyClass { public void myMethod() { // 公共方法 } }
2. protected: The access permission of the protected modifier is between public and private. Classes, methods and variables modified by protected can be accessed by other classes in the same package, or by subclasses in different packages. However, non-subclasses in different packages cannot access protected members. For example:
java protected class MyClass { protected void myMethod() { // 受保护的方法 } }
3. private: private is the strictest access control modifier. Classes, methods and variables modified by private can only be accessed in the same class. Other classes cannot directly access members modified by private. For example:
java public class MyClass { private int myVariable; private void myMethod() { // 私有方法 } }
4. Default access modifier: When no access control modifier is used, the default access permission is package-level access permission. Classes, methods, and variables modified by the default access modifier can be accessed by other classes in the same package, but classes in different packages cannot. For example:
java class MyClass { void myMethod() { // 默认访问方法 } }
To summarize, the access control modifiers in Java include public, protected, private and default access modifiers. Understanding the usage rules and access permissions of these modifiers can help developers better control the access permissions of classes, methods, and variables, and improve the security and maintainability of the code.
The above is the detailed content of What are the java access control modifiers?. For more information, please follow other related articles on the PHP Chinese website!