Why is access control mechanism designed in Java? There are two main functions:
(1) In order for users to avoid touching parts that they should not touch, these parts are necessary for internal operations, but they are not part of the interface required by the client programmer.
(2) In order to enable class library designers to change the internal workings of classes without worrying about having a significant impact on users.
The level of access permission control in Java is:
Public -> protected -> Package access (no permission modifier) -> private.
1. Package
The concept of packages in Java is very similar to the concept of namespaces in C++, and both can limit the scope of classes. The biggest difference between the two is that the packages in Java implicitly indicate the tree hierarchy of the class (and also the directory structure of the Java source code file). The advantage of this is that the uniqueness of the class can be restricted by the requirements for file path uniqueness in the file system.
1. Code organization
When writing a Java source code file (.java file), this file is usually called a compilation unit. At most one public class is allowed in the compilation unit, and the name of the class must be exactly the same as the file name (including upper and lower case).
When compiling a .java file, each class in the .java file will have a .class output file, and the file name and class name are the same. A Java runnable program is a set of .class files that can be packaged and compressed into a Java document file (JAR package, using Java's jar document generator). The Java interpreter is responsible for the search, loading and interpretation of these files.
A class library is actually a set of class files. Each .java file is allowed to have at most one public class, as well as any number of non-public classes. Therefore, each file has a artifact. If you want to organize these components (each build has a .java file and several .class files) to form different groups, you can use the keyword package in Java.
2. The function of package
(1) Organize classes or interfaces with similar or related functions in the same package to facilitate the search and use of classes.
(2) Like folders, packages also use tree-shaped directories to store them. The class names in the same package are different, and the names of classes in different packages can be the same. When classes with the same class name in two different packages are called at the same time, the package name should be added to distinguish them. Therefore, the package can avoid name conflicts.
(3) Packages also limit access rights. Only classes with package access rights can access classes in a package.
3. Create a package
In Java, use the package keyword to specify the package (namespace) to which the code belongs.
Syntax format:
package pkg1[. pkg2[. pkg3…]];
Note:
(1) The name of the package implicitly points out the directory structure of the code.
(2) The public class name (also the Java file name) in the same directory should be unique.
(3) The package declaration should be on the first line of the source file. Each source file can only have one package declaration, and each type in this file is applied to it.
(4) If a source file does not use a package declaration, then the classes, functions, enums, comments, etc. in it will be placed in an unnamed package.
(5) The names of packages are generally in lowercase letters.
For example:
Check the source code of the java.util.ArrayList class and you can see that the first line of the file is:
package java.util;
Its code directory structure is java/util/ArrayList.java
4. Import package
In Java, use the import keyword to import packages.
Syntax format:
import package1[.package2…].(classname|*);
example:
Let’s take java.util.ArrayList as an example. It is very inconvenient to use it in a way that has a full class path.
java.util.ArrayList<String> list = new java.util.ArrayList<String>();
If you want to omit the previous path, you can use the import keyword.
import java.util.ArrayList;
After importing the package in the file, the previous code that declares the list can be simplified as follows:
ArrayList<String> list = new ArrayList<String>();
2. Access rights modifiers
1. package: package access permissions
If no access modifier is provided, it means it is package access.
The default access has no keywords, but it usually refers to package access (sometimes also expressed as friendly, a bit like the concept of friend elements in C++). This means that all other classes in the package can access this member or method, but all classes outside of this package cannot be accessed.
example:
com.notes.packages.test.Info
package com.notes.packages.test;publicclass Info { void print() { System.out.println("default method -- print()"); }}com.notes.packages.test.PublicDemo01
package com.notes.packages.test;publicclass PublicDemo01 { publicstaticvoid main(String[] args) { Info x = new Info(); x.print(); }}PublicDemo01 and Info can access the default-level method of Info - print() under the same package.
com.notes.packages.PublicDemo02
package com.notes.packages;import com.notes.packages.test.Info;publicclass PublicDemo02 { publicstaticvoid main(String[] args) { Info x = new Info(); // x.print(); // Error }}PublicDemo02 and Info are not in the same package, and the method of Info's package access permission level cannot be accessed - print().
2. public: interface access permissions
Using the public keyword means that the declared member or method is accessible to everyone.
Example: If the print() method permission in the default level permission example is set to public, PublicDemo02 can be accessed.
package com.notes.packages.test;publicclass Info { publicvoid print() { System.out.println("public method -- print()"); }}3. Private: Unable to access
Using the private keyword means that the declared member or method is inaccessible to any other class except this class.
Application scenario: Singleton mode
4. protected: inherit access permissions
A new class (called a child class or a derived class) can reuse an existing class (called a parent class or a base class) through inheritance, and then extend the members and methods of the base class. Sometimes, the creator of a base class will want a specific member to assign its access to the derived class instead of all classes. Public cannot do this, and for this purpose, protected was introduced to do the job. protected also provides package access, that is, derived classes and other classes within the same package can access protected members or methods.
Example: After the subclass inherits the parent class, it can access the protected members of the parent class.
class Father { private String a = "private"; protected String b = "protected"; public String c = "public";}; class Son extends Father { publicvoid print() { // System.out.println("element a:" + super.a); // Error System.out.println("element b:" + super.b); System.out.println("element c:" + super.c); }} publicclass ProtectedDemo01 { publicstaticvoid main(String args[]) { Son sub = new Son(); sub.print(); }};Notes on access modifiers
In the previous examples, the members and methods of the class can be modified with various permission modifiers.
In addition, there are some points to pay attention to:
(1) The usage of permission modifiers for static members and static methods is the same as that of ordinary members and methods.
(2) Although the class can also be modified by modifiers, the two permission rhetorical words private and protected cannot be used.
(3) In some books, package access is also called default access. I personally do not recommend memorizing this way, because this is easily confused with the new feature of Java Se8 - the default keyword. This keyword can only be used for Interface, and its function is to allow programmers to define the default implementation of interfaces in Interface (in the past JDK versions did not allow this, you can only declare methods in the interface).
The above is all about this article, I hope it will be helpful to everyone's learning.