Access Control in Java

Source: Internet
Author: User
1. programmers who use C language may be used to accessing all things without any restrictions. This is not a bad idea. It may be very good in the Age of personal heroes, but now there are hundreds of thousands of lines of code in software engineering, I have never been able to do anything for a single programmer. Now I am talking about teamwork. To solve the naming and communication problems between multiple programmers, c ++ puts forward the concepts of access control and namespace, and access control is also the main means to implement hiding in object-oriented systems. why hide it? Let's talk about it first. Specifically, we can study object-oriented programming. "When Designing object-oriented design, a basic consideration is: how to separate changing things from unchanged things."

This is especially important for libraries. The user (client programmer) of that database must be able to rely on the part used by the user, and know that once the new version of the database is released, the Code does not need to be rewritten. On the contrary, the creator of the library must be able to modify and improve freely, and ensure that the customer's programmer code will not be affected by those changes.
For this purpose, certain conventions or rules must be observed. For example, when a library programmer modifies a class in the library, he must ensure that the existing method is not deleted, because doing so will cause the client programmer to break the code. However, the opposite is painful. For a data member, how can the database creator know which data members have been accessed by client programmers? If a method is a unique part of a class and is not necessarily directly used by the client programmer, the pain is also true. What should I do if the database creator wants to delete an old Implementation Scheme and add new code? Any changes made to those Members may interrupt the code of the client programmer. Therefore, the database creator is in an awkward situation and seems to be unable to move at all.
To solve this problem, Java introduces the concept of "access indicator", allowing the database creator to declare what is available to the client programmer and what is unavailable. The access control level is between "maximum access" and "minimum access", including public, "friendly" (No keyword), protected, and private. According to the description in the previous section, we may have concluded that as a Database Designer, we should keep everything as private as possible ), and only show the methods to be used by the client programmers. This idea is completely correct, although it is somewhat contrary to the intuition of those who program in other languages (especially C), who are used to accessing everything without any restrictions. At the end of this chapter, you should be able to deeply understand the value of Java access control. 2. the differences between Java access control and C ++ are specific to each definition of each member in the class. The Java access indicator is poublic, both protected and private are placed at the forefront of them-whether they are a data member or a method. Each access indicator only controls access to that specific definition. This is significantly different from C ++. In C ++, the access indicator controls all definitions after it until another access indicator is added. if the access control operator is not specified in the "friendly" Java class, the default access permission is the current package, l that is, all the classes in the current package can access this "friendly" member. (friendly access makes all the classes seem meaningful under a package.) package myjava. control; pubic class accesscontroldemo {public accesscontroldemo () {system. out. println ("this is accesscontroldemo");} string getstring () // friendly {return "this is function getstring" ;}} accesscontroldemo. java must reside in a sub-directory named control, and this sub-directory must be located in m specified by classpath Under the yjava directory, do not mistakenly think that Java regards the current directory as the start point for searching anyway. If you do not use "." As part of classpath, Java will not consider the current directory 4. Public: interface access
When the public keyword is used, it means that the member declaration followed by the public applies to everyone, especially to client programmers who use the library import myjava. Control .*;

Public class demo {
Public demo (){
System. Out. println ("demo constructor ");
}
Public static void main (string [] ARGs ){
Accesscontroldemo A = new accesscontroldemo // create accesscontroldemo object A. getstring (); // This row has an error. getstring () can only be accessed by classes in the control package}
} 5. Default package class cake {
Public static void main (string [] ARGs ){
Pie x = new pie ();
X. F ();
}
} In the second file in the same directory:


//: Pie.java// The other classclass Pie {  void f() { System.out.println("Pie.f()"); }} 
They may initially be treated as completely unrelated files, but cake can create a pie object and call its F () method! The general idea is that pie and F () are "friendly", so they are not applicable to cake. They are indeed friendly-these conclusions are very correct. However, they can still be used in cake. Java because they are in the same directory and there is no clear package name. Java regards files like this as part of the "Default package" of the Directory, so they are "friendly" for other files in the directory.
6. Private (private)
The private keyword means that unless that particular class,
And from the method of that class, otherwise no one can access that member. Other members in the same package cannot access private members,
This makes it seem that the class is isolated from ourselves. On the other hand, a package cannot be created by several partners. So private allows us to change the member freely without worrying about whether it will affect another class in the same package.
The default "friendly" package access is usually an appropriate way to hide it. Remember that for package users, they cannot access a "friendly" member. This effect is often satisfactory, because the default access method is usually used. For members who want to become public, we usually explicitly point out that it can be freely called by client programmers.
In addition, as a result, you usually think that you do not need to frequently use the private keyword at the beginning, because you can release your own code without using it (this is a stark contrast with C ++ ). However, as learning goes deeper,
We will find that private is still very important, especially when multithreading is involved.
Private sample program
class Sundae {  private Sundae() {}  static Sundae makeASundae() {     return new Sundae();   }}public class IceCream {  public static void main(String[] args) {    //! Sundae x = new Sundae();    Sundae x = Sundae.makeASundae();  }} 
This example proves the convenience of using private: Sometimes you may want to control the object creation method,
And prevent direct access to a specific Builder (or all builders ). In the above example, we cannot create a sundae object through its builder;
Instead, you must call the makeasundae () method.
At this time, it will have another impact: Because the default builder is unique to get the definition, and its attribute is private, it can prevent inheritance of this class.
 
7. Protected (protected)
The access control set by protected is mainly used to inherit classes. Let's talk about inheritance later.

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.