This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

How are access rights controlled in Java?

Access control permissions in Java can be divided into four levels: public, protected, Default, and private. Show a picture that you look at many times but don’t always remember.

For example, I can access a property or method in the same class with whatever access modifier you use. In a subclass, you can only access properties or methods that are protected public from the parent class.

private

If a member method or member variable or inner class name is preceded by a private access control character, the member can only be used inside the class. Only the current class is accessible.

protected

Protected access control. This is an access control that applies to the parent class. If the parent class and the child class are not in the same package and you want to inherit the members of the parent class but you don’t want to make them public, you can make them protected. It mainly serves inheritance.

default

Access control permission of default, that is, if no access modifier is added, the same package can be accessed. The concept of a package is similar to the concept of a namespace, where the keyword package can be used to specify a package, which is displayed at the physical level as a layer of directory structure. The definition of a package helps modularize programming so that I can open only one common interface to use within a package. This greatly protects the secrecy of the implementation in the package, and the function can be implemented secretly without the caller knowing how to implement it!

public

If a member method or variable name is preceded by a public access control character, the member can be accessed by all classes, regardless of whether the accessing class is in the same package as the accessed class.

conclusion

This is the description of access control permissions. So why do you need access control rights? Access control permissions are basically restrictions on how you can call. In Java, one is to keep users from touching parts that they shouldn’t, that are necessary for operations inside a class, but are not part of the interface required by the client programmer. The other is to allow library designers to make changes to the inner workings of classes without worrying about significant impact on users. Of course, these access control characters are also a prerequisite for encapsulation in Java.