Analysis of access control permissions in Java _java

Source: Internet
Author: User
Tags modifier modifiers

Why do you design access control mechanisms in Java? The main function has two points:

(1) In order for the user not to touch the parts that they should not touch, these parts are necessary for the internal operation of the class, but it is not part of the interface required by the client programmer.

(2) To allow class library designers to make changes to the internal work of the class without worrying about a significant user impact.

The level of access control in Java, in order of permissions from large to small:

Public-> protected-> package access (without permission modifiers)-> private.

One, package (package)

The concept of a Java Package (package) is similar to the concept of a namespace (namespace) in C + + to restrict the scope of a class. The biggest difference is that the Baoyin in Java indicates the tree hierarchy of classes (and also the directory structure of Java source files). The advantage of this is that the uniqueness of the class can be limited by the requirement for file path uniqueness in the file system.

1. Code Organization

When writing a Java source code file (. java file), this file is often referred to as a compilation unit. There is a maximum of one public class allowed within the compilation unit, and the class name must be exactly the same as the file name (including capitalization).

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

A class library is actually a set of class files. Each. java file allows a maximum of one public class, as well as any number of non-public classes. Therefore, each file has a widget. If you want to organize these artifacts (each build has a. java file and several. class files) to form different groups, you can use the keyword package in java.

2, the role of the package (package)

(1) The function of similar or related classes or interfaces organized in the same package, convenient for the search and use of the class.

(2) Like a folder, the package also uses a tree-shaped directory storage method. The class names in the same package are different, and the names of the classes in the different packages can be the same, and when you call a class with the same class name in two different packages, you should add the package name to distinguish it. Therefore, packages can avoid name collisions.

(3) Packages also qualify access, and classes that have package access can access classes in a package.

3. Create Package

Java, use the package keyword to specify the package (namespace) to which the code belongs.

Syntax format:

Package pkg1[. pkg2[. Pkg3 ...]];

Note the point:

(1) The name of the package implicitly indicates the directory structure of the code.

(2) The public class name (and also the Java filename) under the same directory should be unique.

(3) The package declaration should be in the first line of the source file, each source file can have only one package declaration, and each type in the file should be applied to it.

(4) If the package declaration is not used in a source file, the class, function, enumeration, annotation, etc. will be placed in an unnamed package (unnamed package).

(5) Package's name is generally all lowercase letters.

For example:

To view the source code of 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, import a package using the Import keyword.

Syntax format:

Import Package1[.package2 ...]. (classname|*);

Cases:

or java.util.ArrayList to give an example. It is inconvenient to use it in a way that is a full path to a class.

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;

The code for the preceding declaration list can be simplified as follows when the import import package is used in the file:

arraylist<string> list = new arraylist<string> ();

Second, access rights modifiers

1, Package: Package access rights

If you do not provide any access modifiers, it means that it is a package access right.

The default access rights do not have any keywords, but usually refer to package access (sometimes expressed as friendly, somewhat like a friend concept in C + +). This means that all other classes in the package can access the member or method, but all classes outside the package are inaccessible.

Cases:

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 under the same package and have access to 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 under a package, you cannot access the method--print () of the info's package access permission level.

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 access it.

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: Single case mode

4, Protected: Inherited access rights

A new class (called a subclass or derived class) can reuse an existing class (called a parent class or base class) through inheritance, and then extend the members of the base class, methods. Sometimes the creator of a base class expects a particular member to give its access to a derived class instead of to all classes. Public could not do this, and for this reason, protected was introduced to complete the work. Protected also provides package access, meaning that derived classes and other classes within the same package can access protected members or methods.

Example: After a subclass inherits a 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 ();

  }

;

The attention point of the access permission modifier

The members of the class are shown in the preceding examples, and methods can be decorated with various permission modifiers.

In addition, there are some points to note:

(1) Static members, static methods, and the use of the right modifier is the same as ordinary members, methods.

(2) Although the class can also be modified to modify the word, but can not use private, protected two rights rhetoric words.

(3) In some books, the package access is also called the default access permission. Personally, this is not recommended, as it can easily be confused with the new feature--default keyword in the Java Se8. This keyword can only be used for interface, which allows programmers to define the default implementation of interfaces in interface (previously JDK versions are not allowed, you can only declare methods in interfaces).

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.