Thinking in Java Notes (sixth chapter access control)

Source: Internet
Author: User
Tags modifiers

Chapter Sixth Introduction to access rights control

Java provides access modifiers that the class library developer can use to indicate to the client programmer what is available and what is not. The level of access control, from maximum permissions to minimum permissions, is:public,protected, Package (library) access (no keywords), and private.

6.1 Package (Library): Gallery unit

The package contains a set of classes that are organized together under a single name control. For example, there is a tool library in Java's standard publication, which is organized under the java.util namespace. java. there is a class called ArrayList in Util, one way to use ArrayList is to specify it with its full name java.util.ArrayList . For example:

public class Test {    public static void main(String[] args) {        java.util.ArrayList list = new java.util.ArrayList();    }}

Have you ever felt very long and troublesome to import the class using the Import keyword, for example:

import java.util.ArrayListpublic class Test {    public static void main(String[] args) {        ArrayList list = new ArrayList();    }}

We need to give the class A namespace by importing. If you have two names for the Stack class and are on the same machine, you need to have full control over the namespace, and attach a unique label to each class.

When writing a Java source code file, this file is usually compiled as a compilation unit, and each compilation unit must be named by a suffix . java, within the compilation unit can have a class that is decorated with the public key, The name of the class must be the same as the file name, or the compiler will error. If there are additional classes in the compilation unit, these classes are not public and cannot be seen outside the package.

6.1.1 Code Organization

When compiling a . Java file, each class in the file will have an output file with the same filename and class name, and a . class suffix. Therefore, after compiling a small number of . Java files, there may be many . class files, if in a compiled language (for example, c), the intermediate files produced after compilation (usually an obj file), and then through the linker (to create an executable file) or a class library generator (librarian, used to create a class library) to produce other homogeneous file bindings together.

But this is not how Java works, and the Java runnable program is a set of . Class files that can be packaged and compressed into a Java document file (jar, which uses Java's jar document Generator). The Java interpreter is responsible for locating, loading, and interpreting these files.

A class library is actually a set of class files. Each of these files has a public class, and a non-public class with a number of people. If you want a . java file to belong to the same group, you can use the package keyword.

The package statement must be the first line of code in a compilation unit (. java file) other than comments. For example package access; . Indicates that the class is part of the class library named Access . For example

package access.mypackage;public class MyClass {    .....}

After you have defined the class MyClass and assigned the package name, you need to import the class with the keyword import if you need to use the class.

import access.mypackage.*;public class Test {    public static void main(String[] args) {        MyClass class = new MyClass();    }}
6.1.2 Create a unique package name

To avoid multiple packages of files being mixed in the same directory, it is logical to place all of the . Class files for a particular package in one directory. Use the hierarchical file structure of the operating system to solve this problem.

Earning a subdirectory of all your files can also solve two additional problems:

    1. By convention, the first part of the package name is the anti-order Internet domain name of the creator of the class, and if named by management, the package name will also be unique, preventing name collisions.
    2. Decompose the package name into a directory on the cost machine. When the Java program runs and loads the required . class files, it is straightforward to determine the directory in which the files are located.

The Java interpreter runs as follows: Identify the environment variable classpath (which can be set by the operating system), Classpath contains one or more directories to use as the root directory for finding. class files. Starting at the root, the interpreter gets the name of the package and replaces each period with a backslash to produce a path name from the Classpath root (for example, the package name Foo.bar.baz becomes foo\bar\baz or Foo/bar/baz, depending on the operating system). The resulting path will be combined with the corresponding directory in Classpath, where the interpreter looks for and needs to create the same. class file with the same name.

6.1.3 Notice of use of the package

Whenever a package is created, the directory structure is implicitly specified when the package name is given. The package must be in the directory specified by its name, and the directory must be available in the directory where the Classpath begins. Note that the compiled code is usually placed in a different directory than the source code, but it must be ensured that JVN uses Classpath to find the path .

6.2 Java Access keyword

Public , protected, private These Java access modifier words are used when they are placed in the definition of each member of a class, whether the member is a method or a variable. If you do not provide any form of access modification, it means that it is package access.

6.2.1 Packages (Package) access rights

The default access permission in a class does not have any keywords, but it usually refers to package access (sometimes also called friendly). This means that all other classes in the current package have access to the member, but for all classes outside of the package, the private feature is displayed.

Package access allows all related classes within a package to be combined so that they can interact easily. When classes are organized into a package, they are given access to each other's members.

6.2.2 Public: Interface access rights

The use of the keyword public also means that the member immediately following it is directly accessible to anyone, assuming that a dessert package is defined that contains a compilation unit:

package access.dessert;public class Cookie {    public Cookie() {        System.out.println("Cookie constructor");    }    void bite() {        System.out.println("bite");    }}

Now if you create a program that uses the cookie class:

import access.dessert.*;public class Dinner {    public static void main(String[] args) {        Cookie x = new Cookie();    }}

This makes it possible to create a cookie object, but the method cannot be accessed because the Bite method is in-package access and is not within a package.

Default Package : If none of the two classes are indicated by the package keyword, the file you belong to is in the default package for that directory, and if the two classes are in the same subdirectory, you can access the members of the package access permissions to each other. If the two class files in the example above are in the same directory, the method can be called x.bite() , otherwise an error will be given.

6.2.3 Private: Unable to access

The keyword private means that, in addition to the class that contains the member, no other class can access the member. The following example uses the private keyword:

class Sundae{    private Sudae() {        static Sudae makeASudae(){        return new Sudae();    }}public class IceCream {    public static void main(String[] args) {        Sundae x = Sundae.makeSundae();    }}

This example prevents the external direct contact with the constructor, and creates an instance of the class with the constructor provided by the author.

Any method that is certain to be an "assistant" to the class can be designated as privateto ensure that it is not misused elsewhere in the package.

6.2.4 protected: Inheriting access rights

The keyword protected deals with the concept of inheritance, where you can take advantage of a base class and then add new members to an existing class without touching the existing class. You can also change the behavior of existing members of that class.

If you create a new package and inherit the base class from another package, the only member that can be accessed is the public member in the base class. The creator of a base class would want a particular member to assign its access rights to its subclasses rather than all classes, which would require the protected keyword. protected also provides package access, that is, the default access for the enhanced version, except that classes in the same package can be accessed, as well as inheriting its class access. The following example:

//Cookie.javapackage access.dessert;public class Cookie {    public Cookie() {        System.out.println("Cookie constructor");    }    void bite() {        System.out.println("bite");    }}

Currently, only the same package has access to the method bite () .
If you create another class to inherit the cookie and change the access permission of the Bite () method to protected

//SmallCookie.javapackage dada.lifepublic class SmallCookie extends Cookie{    public SmallCookie() {        System.out.println("SmallCookie constructor"):    }    public void smallBite() {        bite();    }    public static void main() {        SmallCookie sc = new SmallCookie();        sc.smallBite();    }}

At this time Smallcookie has access to the bite () method in the cookie.

Access rights for Class 6.4

In Java, access permission modifiers can also be used to determine which classes in the library are available to the consumer.

In order to control access permissions for a class, the modifier must appear before the keyword class . For example, there are public class Widget{} some caveats when using keywords to restrict access:

    1. Each compilation unit (file) can have only one public class. Each compilation unit has a single common interface, which is decorated with public.
    2. A class that is decorated with public must have the same name as the compilation unit (file), including case.

Note that the access rights of a class can neither be private(which makes it inaccessible to any other class) and cannot be protected . So access to a class has only two choices: package access or public. If you do not want anyone else to have access to the class, you can set all constructors to private.

If you do not specify an access modifier for the class access permission, it will get the package access by default. This means that objects of this class can be created by any other class within the package, but not outside the package. (at the beginning of the class, the package name specified by the packages is considered under the same package, and the default package name ~) is also required.

Thinking in Java Notes (sixth chapter access control)

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.