Introduction to access control

Source: Internet
Author: User
This section describes the access control-general Linux technology-Linux programming and kernel information. The following is a detailed description. We know that encapsulation connects data with the code for processing data. Encapsulation also provides another important attribute: access control ). By encapsulating it, you can control which part of the program can be a member of the category class. By controlling access, you can prevent object abuse. For example, by allowing only a set of appropriately defined methods to access data, you can prevent misuse of the data. Therefore, if used properly, you can create a "black box" for the class. Although this class can be used, its internal mechanism is not public and cannot be modified. However, the classes created earlier in this book may not be fully suited to this goal. For example, consider the Stack class at the end of Chapter 6th. The push () and pop () methods do provide a controllable interface for the stack. This is a fact, but this interface is not enforced. That is to say, it is possible that other parts of the program can bypass these methods to directly access the stack. Of course, improper use may cause trouble. This section describes how to precisely control the access of various members of a class.

How a member is accessed depends on the access specifier that modifies its declaration ). Java provides a rich set of access indicators. Some aspects of access control are mainly associated with inheritance or packages (packages and packages are essentially a group of classes ). These access control mechanisms of Java will be discussed later. Now, let's start with a simple class for access control. Once you understand the basic principle of access control, it is easier for others.

Java access indicators include public (public, global), private (private, local), and protected (protected ). Java also defines a default access level. The indicator protected is only used for inheritance. The other two access indicators are described below.

Let's start with defining public and private. When a class member is modified by a public indicator, the member can be accessed by any other code in your program. When a class member is specified as private, the member can only be accessed by other Members in its class. Now you can understand why main () is always modified by the public indicator. It is called by code outside the program, that is, it is called by the Java running system. If you do not use an access indicator, the default access to this type of member is set to public in its own package, but it cannot be accessed outside of its package (the package will be discussed later ).

So far, all the members of the class we developed have used the default access mode, which is essentially public. However, this is not a typical method you want. Generally, you want to restrict access to data-like members by using methods only. In addition, sometimes you want to define a method as a private method of the class.

The access indicator is located before other descriptions of the member type. That is, the statement must begin with an access indicator. The following is an example:

Public int I;
Private double j;

Private int myMethod (int a, char B ){//...

To understand the effect of public and private on access, see the following program:

/* This program demonstrates the difference

Public and private.

*/

Class Test {

Int a; // default access

Public int B; // public access

Private int c; // private access

// Methods to access c

Void setc (int I) {// set c's value

C = I ;}

Int getc () {// get c's value

Return c;
}
}

Class AccessTest {
Public static void main (String args []) {
Test ob = new Test ();

// These are OK, a and B may be accessed directlyob. a = 10; ob. B = 20;

// This is not OK and will cause an error
// Ob. c = 100; // Error!

// You must access c through its methodsob. setc (100); // OKSystem. out. println ("a, B, and c:" + ob. a + "" +

Ob. B + "" + ob. getc ());
}
}

It can be seen that in the Test class, a uses the default access indicator, which is the same as public in this example. B is explicitly specified as public. The member c is specified as private, so it cannot be accessed by code outside its class. Therefore, c cannot be used directly in the AccessTest class. You can only access it through its public Methods: setc () and getc (). If you remove the annotator at the beginning of the following statement,

// Ob. c = 100; // Error!

You cannot compile this program because of violation. To understand the application of access control in practice, let's look at the improved version of the Stack class shown at the end of Chapter 6th.

// This class defines an integer stack that can hold 10 values.
Class Stack {

/* Now, both stck and tos are private. This means that they cannot be accidentally or maliciouslyaltered in a way that wocould be harmful to the stack.

*/Private int stck [] = new int [10]; private int tos;

// Initialize top-of-stack
Stack (){
Tos =-1;
}

// Push an item onto the stack void push (int item) {if (tos = 9) System. out. println ("Stack is full."); else

Stck [++ tos] = item;} // Pop an item from the stack
Int pop (){

If (tos <0) {System. out. println ("Stack underflow."); return 0;

}
Else
Return stck [tos --];
}
}

In this example, the stck of the storage stack and the subscript tos pointing to the top of the stack are both specified as private. This means that they cannot be accessed or changed except through push () or pop. For example, specifying tos as private prevents other parts of your program from inadvertently setting its value to a value that exceeds the stck array's bottom mark.

The following program shows the improved Stack class. Try to delete the comment above to prove that stck and tos members are indeed inaccessible.

Class TestStack {

Public static void main (String args []) {
Stack mystack1 = new Stack ();
Stack mystack2 = new Stack ();

// Push some numbers onto the stack
For (int I = 0; I <10; I ++) mystack1.push (I );
For (int I = 10; I <20; I ++) mystack2.push (I );

// Pop those numbers off the stack
System. out. println ("Stack in mystack1 :");
For (int I = 0; I <10; I ++)

System. out. println (mystack1.pop ());

System. out. println ("Stack in mystack2 :");
For (int I = 0; I <10; I ++)
System. out. println (mystack2.pop ());

// These statements are not legal
// Mystack1.tos =-2;
// Mystack2.stck [3] = 100;

}
}

Although methods defined by classes generally provide access to data, this is not always the case. It is entirely appropriate to allow an instance variable to be public when necessary. For example, for simplicity, most simple classes in this book do not care about the access to instance variables when they are created. However, in most practical classes, it is necessary to allow data operations only through methods. The next chapter will go back to the access control topic. You will see that access control is crucial in inheritance.
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.