Java Road (v) Access rights control

Source: Internet
Author: User
Tags modifiers

In Java, all things have some form of access control.

The control level for access is from maximum to minimum: public,protected, package access (no keywords), and private.

Public,protected and private These Java access modifiers are used before each member of the class (domain or method) is defined.

I. Access rights for CLASS members

The only way to gain access to a member is to:

1). Make the member public. No matter who is where, you can access the member;

2). Give a member access to a package by means of a modifier that does not have access, and by placing other classes in the same package, other classes within the package can access the member;

3). Inherited classes can access both public members and protected members.

4). Provides accessor and mutation methods to read and change values.

1. Package access rights

The default access permission does not have any keywords, but by means of the package access permission, which means that all other classes in the current newspaper have access to that member, but for all classes outside of this package, this member is private.

Package access permissions combine all the related classes within a package so that they can interact easily with each other.

Note: If two classes are in the same directory, and no package names are set for themselves, Java automatically considers such files to be part of the default package that belongs to the directory, and the files have packet access to each other .

The following example illustrates the problem:

// class cake and pie are in the same directory and are not explicitly displayed in any package class pie{    void  f () {        System.out.println ("pie.f ()");}    } class cake{    publicstaticvoid  main (string[] args) {          New Pie ();          X.F ();     }} // output is pie.f ()

2.public: Interface access rights

Using the keyword public means that subsequent member declarations are available to everyone, especially to the client programmer who uses the class library.

3.private: You cannot access

The keyword private represents the class that contains the member, and no other class can access the member. Other classes within the same package do not have access to private members of this class, so this is tantamount to isolating themselves.

  This function of the private keyword has many uses, such as controlling how objects are created, preventing others from accessing a particular constructor (or all constructors) directly. Look at the following example:

class sundae{    private  sundae () {}    static  Sundae Makeasundae () {         return New sundae ();    }}  Public class icecream {    publicstaticvoid  main (string[] args) {        = Sundae.makeasundae ();    }}

In this example, we can create the Sundae object by calling the Makeasundae () method, but it cannot be created by the constructor.

This is also true for private domains in classes.

However, it is important to note that because a reference to an object in a class is private, it is assumed that the other object cannot have a public reference to the object.

4.protected: Inherit access rights

If you create a new package and inherit the class from another package, the only member that can be accessed is the public member of the source package.

Sometimes, the creator of a base class wants to assign access to a particular member to a derived class rather than to all classes, which is implemented using the keyword protected.

Note thatprotected also provides package access, which means that other classes within the same package can also access the protected elements of this class.

Second, interface and implementation

The control of access rights is often referred to as the concealment of specific implementations.

Wrapping data and methods into classes, and the concealment of concrete implementations, are often collectively referred to as encapsulation.

For two important reasons, access control delimits the bounds of a permission within the data type:

1. To set the bounds that the client programmer can and cannot use. You can build your own internal mechanisms in the structure, without worrying that the client programmer will accidentally take the internal mechanism as part of the interface they are using.

2. The interface and the specific implementation are separated.

Iii. access rights for classes

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

Modifiers must be placed before the keyword class. For example:

 Public class widget{...} or Improt access. Widgets;

You know, a class can not be private (if the class is private, then no other class can access it except for that class), nor can it be protected (in fact an inner class can be private or protected, However, this is an exception, as described in the following article), which can only be a package access or public.

If you do not want other people to access the class, you can designate all constructors for that class as private, preventing anyone from creating objects of that class. However, there are exceptions, and this does not prevent you from creating the class inside the static member of the class. Let's look at the example below:

classsoup1{PrivateSoup1 () {} Public StaticSoup1 Makesoup () {//creating an object using a static method        return NewSoup1 (); }}classsoup2{PrivateSoup2 () {}Private StaticSoup2 PS1 =NewSoup2 ();//create an object using singleton mode     Public StaticSoup2 Access () {returnPS1; }     Public voidf () {}} Public classLunch {voidtestprivate () {//Soup1 soup = new Soup1;    }    voidTestsingleton () {soup2.access (). f (); }}

As we can see, the constructors for the Soup1 and Soup2 classes are private, and no one is able to use the constructor directly to create objects of that class. But we can also use these two classes: Create a static method in Soup1, use the constructor in this method to create a Soup1 object and return its reference; the creation of SOUP2 uses the singleton pattern in design mode and only one of its objects can be created. The object of the Soup2 class is created as a static private member of the SOUP2, so there is only one, and it cannot be accessed unless access () is through the public method.

In addition, some limitations also merit attention:

1. Each compilation unit can have only one public class.

The name of the 2.public class must match exactly the file name contained in the compilation unit, including case.

3. If there is no class with public in the compilation unit, you can name the file arbitrarily.

Java Road (v) Access rights control

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.