In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how Java uses access modifiers, which is very detailed and has certain reference value. Friends who are interested must read it!
1. Introduction
Access modifiers are a basic part of Java syntax, but only a few programmers can use Java access modifiers correctly. In the development of Java components, if access modifiers can be used properly, the internal data of components and implementation details that do not need to be published can be well hidden, thus isolating component API from implementation details. Java components developed correctly using access modifiers can also decouple programs in the process of calling and relying on components, so that the whole component can be continuously developed, tested and updated.
A warm summary of Xiao Zi:
Achieve the effect of information hiding or encapsulation by restricting the access scope, and ensure the security of the program implementation details.
Decoupling components so that the coupling relationship between components is reduced, thus enabling low-cost, low-risk (do not affect other components) iteration
2. Access modifier
The Java syntax provides four levels of access modifiers that act on fields, methods, classes, and interfaces, and their accessibility is as follows:
The access modifier name accessibility private is private to the class that declares the member. Note: the top-level class cannot be modified by private and protected, the inner class can be privately declared at the default/package-private package level that any class under the same package of the member can access the protected protected declaration of the member under the same package, the subclass can access any place common to the public
Note: private and default are not absolutely secure. If the class implements Serializable, these fields modified by private and defaulte may also be exported; secondary reflection can also cross the restrictions of access modifiers.
3. Principles
The principle used by the Java access modifier is very simple: in the process of implementing Java components, ensure that the functions of the components are consistent, while keeping classes and class members from being accessed by the outside world as much as possible.
This rule may seem very simple, but it is often misleading to the programmer who sets all the methods and properties of the class to private without thinking.
What kind of problem will this lead to? When the components are published or iteratively updated, you need to constantly subvert the previous design and expose more API to the public, but on the whole, this is better than decorating all the members of the class with public, which is totally unacceptable, guys.
Then the question arises. What should we do exactly?
In fact, Xiao feels that there are only three points to understand, because access modifiers act on classes, methods, and properties, so analyze how they should choose access modifiers according to the following three.
There are the following rules for classes:
There is no choice for the API. The default is public.
For the top-level ordinary class, we can choose public and default. At this time, we should focus on whether this top-level class is just the abstraction provided in the current package. If this condition is met, it can be set to default, but if this top-level class needs to be directly used by other classes outside the package, it can only be set to public.
Non-top-level ordinary class, this kind is mainly internal class, the inner class has anonymous inner class, non-anonymous inner class; anonymous inner class does not consider; non-anonymous inner class also has static inner class and non-static inner class. Xiao Xiao thinks that there is no difference between the two when choosing access modifiers, and choose private as much as possible, because you both design it as an inner class, indicating that this class abstraction is to provide abstract support for the outer class. So for the sake of component design security, make it private as much as possible, and if you need to use it externally, you can provide API access through outer classes.
There are the following rules for methods:
There is no choice for the interface method. The default is public. According to the Richter replacement principle, subclass instances can be used wherever superclasses are used. The access modifiers of subclasses must be greater than or equal to superclasses, so there is only one choice for subclasses: public.
For ordinary class methods, before designing a class, you should first design the API that the class needs to publish, that is, the functions / services that the class needs to provide to the outside world. This must be designed before writing the code, and then we will consider designing these API as default, protected, public. The details must be modified with private.
There are the following rules for attributes:
If the class is common, the instance field must not be exposed, because once the instance field is exposed, it means that the instance field can be modified in other classes, and the security of the instance field cannot be guaranteed.
If the property can be defined as a constant, we must modify it with static final so that the exposed domain is more secure. Be careful not to define mutable objects such as arrays in the constant field.
With regard to the danger of defining array objects in the constant field, Xiao Xiao gives a Demo demonstration.
Define the Person object:
Public class Person {private String name; public Person (String name) {this.name = name;} public String getName () {return name;} @ Override public String toString () {return "Person {" name=' "+ name +''+'}';}}
Define the class to which the array field belongs:
Public class PersonDemo {public static final Person [] PERSONS = new Person [] {new Person ("Li Ziqi"), new Person ("Li Ziqi")};}
Test the code:
Class Test {public static void main (String [] args) {Arrays.stream (PersonDemo.PERSONS) .forEach (System.out::println); for (int I = 0; I
< PersonDemo.PERSONS.length; i++) { PersonDemo.PERSONS[i] = new Person(PersonDemo.PERSONS[i].getName() + "被修改啦!"); } System.out.println(); Arrays.stream(PersonDemo.PERSONS).forEach(System.out::println); }} 测试结果可以看出,数组内容被修改了,这往往不是我们定义一个常量时所希望看到的。The handling of this approach is also simple, you can privatize the array field and provide an API to access the copy of the array
Public class PersonDemo {private static final Person [] PERSONS = new Person [] {new Person ("Li Ziqi"), new Person ("Li Ziqi")}; public static final Person [] getPersons () {return PERSONS.clone ();}}
At this time, the external PERSONS array cannot be accessed directly, only the copy of the array is accessed, and only the copy of the array is modified, which cannot be modified to the contents of the array field.
Alternatively, you can use the Collections utility class to wrap it as an immutable collection. After it is wrapped into a UnmodifiableCollection object, UnsupportedOperationException will be thrown by method calls such as set, add, remove, and so on:
Public class PersonDemo {private static final Person [] PERSONS = new Person [] {new Person ("Li Ziqi"), new Person ("Li Ziqi")}; public static final List getPersons () {return Collections.unmodifiableList (Arrays.asList (PERSONS));}} above is all the content of the article "how to use the access modifier for Java". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.