A brief analysis of access control rights in Java

  • 2020-05-05 11:16:10
  • OfStack

Why is the access control mechanism designed in Java? There are two main functions of :

(1) in order for users not to touch parts that they should not touch, which are necessary for operations inside the class, but are not part of the interface required by the client programmer.

(2) to allow the library designer to change the inner workings of the class without having to worry about having a major impact on the user.

The level of access control in   Java, in descending order of permissions:

Public - > protected - > Package access (no permission modifier) -> private.

1. Package (package)

The concept of a package (package) in Java is similar to the concept of a namespace (namespace) in C++, which limits the scope of a class. The biggest difference is that packages in Java implicitly specify the tree hierarchy of the class (which is also the directory structure of the Java source files). The advantage of doing this is that you can limit class uniqueness by requiring file path uniqueness in the file system.

  1, code organization

When you write an Java source file (.java file), this file is often referred to as a compilation unit. A maximum of one public class is allowed in a compilation unit, and the name of the class must be exactly the same as the file name (including case).

When compiling a.java file, each class in the.java file has a.class output file, which is the same as the class name. The Java runnable program is a set of.class files that can be packaged and compressed into an Java document file (JAR package, Java's jar document generator). The Java interpreter is responsible for finding, loading, and interpreting these files.

A class library is really a set of class files. Each of these.java files is allowed to have up to one public class and any number of non-public classes. Therefore, each file has an artifact. If you want to organize these artifacts (one.java file per build and several.class files) into different groups, you can use the keyword package from Java.

  2, package (package)

(1)         organizes classes or interfaces with similar or related functions in the same package to facilitate the search and use of classes.

(2)         packages, like folders, are stored in a tree directory. The names of classes in the same package are different, and the names of classes in different packages can be the same. When two classes with the same class name in different packages are called at the same time, the package name should be added to distinguish them. Therefore, packages can avoid name collisions.

(3) the         package also restricts access, so that a class with package access can access a class in a package.

  3, create package

In Java, the package keyword is used to specify the package (namespace) to which the code belongs.

Syntax:


package pkg1[ . pkg2[ . pkg3 ... ]];

Note:

(1) the name of the         package implicitly indicates 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 have only one package declaration, and each type in this file applies to it.

(4)         if a package declaration is not used in a source file, the classes, functions, enumerations, comments, etc., will be placed in an unnamed package (unnamed package).

(5)         package names are generally all lowercase letters.

For example:

Looking at the source code for the java.util.ArrayList class, you can see the first line of the file:

package java.util;

Its code directory structure is java/util/ArrayList java

4. Import package

In Java, the import keyword is used to import packages.

Syntax:


import package1[.package2 ... ].(classname|*);

Example:

Again, java.util.ArrayList. It is inconvenient to use it as a class full 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 using the import import package in the file, the previous code declaring list can be simplified as follows:


ArrayList<String> list = new ArrayList<String>();

2. Access modifier

1, package: package access permission

If no access modifier is provided, it means that it is package access.

The default access does not have any keywords, but usually refers to package access (sometimes also referred to as friendly, somewhat like the friend concept in C++). This means that all other classes in the package can access this member or method, but no classes outside the package can.

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 are in the same package, and you can access Info's default level method -- print().

  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, so you cannot access the package access level method of Info -- print().

  2, public: interface access rights

Using the public keyword means that the declared member or method is accessible to all.

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 cannot be accessed by any class other than this class.

Application scenario: singleton mode

  4, protected: inherited access to

New classes (called subclasses or derived classes) can reuse an existing class (called parent class or base class) through inheritance, and then extend the members and methods of the base class. Sometimes, the creator of a base class wants a particular member to have access to a derived class instead of all classes. public could not do this, so protected was introduced to do the job. protected also provides package access, meaning that derived classes and other classes within the same package can access protected members or methods.

Example: after the child class inherits the parent class, it can access the protected member 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();

  }

};

  access modifier points of interest

The previous examples show that class members and methods can be modified with various permission modifiers.

In addition, there are a few points to note:

(1) the permission modifiers of         static members and static methods are used in the same way as ordinary members and methods.

(2) although the class         can also be modified by modifiers, the permission rhetoric words private and protected cannot be used.

(3) package access is also known as default access in some books as        . This is not personally recommended, as it can easily be confused with the new Java Se8 feature, default keyword. This keyword is used only for Interface, which allows programmers to define the default implementation of the interface in Interface (previous versions of JDK do not allow this, you can only declare methods in the interface).

The above is the entire content of this article, I hope to help you with your study.


Related articles: