🔊 This article is posted on ⭐ CS-Wiki (Gitee recommended project, 0.9k star). Welcome star ~ 😊


The foreword 0.

This is an era of crazy technological iteration, where frameworks emerge one after another, but the underlying foundation is the core competency. The blogger (veal) on the basis of the existing knowledge, to the perspective of God on the Basis of Java language review, summary “Java little white growth” series, and strive to from 0 to 1, the full text without pit.

In the first article, we have learned that object-oriented has four basic characteristics:

  • Abstract: Generalize the common properties and behaviors of objects of the same type to form a class. A class is a template or blueprint for constructing an object. The process of constructing an object from a class is called creating an instance of the class.
  • Encapsulation: Encapsulates the abstract data and code together, hides the attributes and implementation details of the object, and only provides public access to the external world. It isolates changes, facilitates use, and improves reusability and security
  • Inheritance: On the basis of existing classes, extend to form a new class, improve code reuse. Inheritance is a prerequisite for polymorphism
  • Polymorphism: the so-called polymorphism is the same function name with different functions

The concepts of abstraction and classes are familiar from the previous four articles. In this article, we will discuss how Java, as an object-oriented programming language, implements encapsulation.

1. What is encapsulation

In object-oriented programming, Encapsulation refers to a method of wrapping and hiding the implementation details of an abstract function interface.

In layman’s terms, encapsulation can be thought of as a protective barrier that prevents a class’s code and data from being randomly accessed by code defined by an external class. To access the code and data of this class, strict access controls are required.

The main feature of encapsulation is that we can modify our own implementation code without modifying the snippets that call our code.

Proper encapsulation makes programs easier to understand and maintain, and also enhances program security.

OK, to summarize the advantages of encapsulation:

  • Good encapsulation reduces coupling
  • The structure inside the class can be modified freely
  • You can have more precise control over member variables
  • Hide information and implement details

2. How does Java implement encapsulation

As mentioned above, strict access control is required to access a encapsulated class, so Java designed a strict access specifier to modify the access of the encapsulated class, from “maximum” to “minimum” :

  • An open –public
  • Protectedprotected
  • Package access (without keywords)
  • Private –private

First, we need to understand that the permissions of a class and the permissions of a field or method in a class can be modified:

  • For fields or methods in a class: all four access modifiers can be used to modify
  • For classes: only package access orpublicCan be used to modify (note this)

So anyway, everything has some form of access control.

3. The concept of packages

Before we learn more about access modifiers, we also need to understand the concept of packages, because although Java designs strict access modifiers, the mechanism is still incomplete. The problem is how to bundle library components into a cohesive library unit. This means how to aggregate some related classes into a large organization for unified management. Java introduces the concept of packages for this purpose, controlling access modifiers through the package keyword, whether a class is in the same package or in a different package. You won’t understand the full meaning of access modifiers until you understand the concept of packages.

As the name implies, a package is used to bring together a group of classes, so it can also be understood as a class library. To bring these classes together, you need to use the keyword package to indicate which package the classes are under.

Note: If you use the package statement, it must be the first line of code in the file other than comments.

💬 For example:

package hiding;

public class MyClass {
    // ...
}
Copy the code

Class access will be covered at the end, but the only thing you need to know is that MyClass is a class that can be accessed by anyone because it is decorated by public

The code above means that the MyClass class is part of a hiding package. Anyone wishing to use the class must specify the full class name or import hiding using the import keyword:

1) The first method: use the import keyword (recommended)

import hiding.mypackage.*;

public class ImportedMyClass {
    public static void main(String[] args) {
        MyClass m = newMyClass(); }}Copy the code

2) The second method: use the full class name

hiding.mypackage.MyClass m = new hiding.mypackage.MyClass();
Copy the code

Thus, with packages, you can not only effectively aggregate classes, but also isolate a single global namespace to avoid name collisions.

4. Access modifiers

With the concept of packages in hand, let’s return to the subject of this article. As we said earlier, each of these four access modifiers can be used to modify a field or method in a class.

That is, if the Java access modifiers public, protected, and private precede the field and method names in a class, they control the objects they modify. If you do not provide an access modifier, it means that the field or method has “package access”.

Let’s explain in detail how these four access modifiers apply to methods and fields in a class 👇

① Package access permission

Now that we know what a package is, what is package access?

Package access means that a member (class, field, method) can be accessed by all methods in the same package if no access modifier is provided, but members outside the package cannot be accessed. Package access rights are also called default access rights.

💬 for example:

package java.awt;

public class Window { 
    String warningString; 
} 
Copy the code

The Cookie class is declared public, which means that all classes can access it

This means that methods of all classes in the java.awt package can access the variable warningString and set it to any value.

To help you visualize this (assuming all classes are public) :

As you can see, package access allows all related classes within a package to be combined so that they can be easily used with each other. Building a package access mechanism is one of the most important reasons for clustering classes in packages.

② Public interface access permission

When you use the keyword public, it means that members (classes, fields, methods) declared immediately after public are available to everyone.

💬 such as:

package A.B; / / a. package

public class Cookie{
	public Cookie(a){ // public Indicates the interface access permission
        System.out.println("Cookie constructor");
    }	
    void bite(a){ // Package access permission
        System.out.println("bite"); }}Copy the code

Use it in another class:

package A; / / A package
import A.B.Cookie.*;
    
public class Dinner{
    public static void main(String[] args){
        Cookie x = new Cookew();
        // x.bite(); can't access}}Copy the code

The constructor of the Cookie class defined here is public and accessible to all classes. The bite() method does not declare an access modifier and has package access, meaning that it only gives access to classes in package A.B, so the bite() method is not accessible to the Dinner class in package A.

To help you visualize this (assuming all classes are public) :

③ Private Private access

The keyword private means that the member cannot be accessed by any class other than the one that contains it. Other classes in the same package cannot access the private member, so this is tantamount to isolating themselves.

💬 for example:

class Cookie{
	private Cookie(a){ 
        System.out.println("Cookie constructor");
    }	
    static Cookie makeACookie(a){
        return newCookie(); }}public class Dinner{
    public static void main(String[] args){
        // Cookie x = new Cookie(); Can't access
        Cookie x = Cookie.makeACookie(); // Can be called through static methods}}Copy the code

To help you visualize this (assuming all classes are public) :

④ Protected inherited access

Protected is the more complex of the four and involves inheritance. For those of you who don’t know anything about inheritance, you can skip this section for now.

First, protected also provides package access, meaning that other classes within the same package can access protected elements that other packages cannot. There is one exception, however, that differs from package access: a child class can access protected access members of its parent class even if the parent class and child class are not in the same package. (For package access, if the subclass and its parent are not in the same package, the subclass cannot access members of the parent class that have package access.)

💬 For example: define a parent class Cookie, subclass ChocolateChip inherits it, and the two classes are not in the same package

package A.B; / / a. package

public class Cookie{
    protected void bite(a){ 
        System.out.println("bite"); }}Copy the code

Subclass inherits Cookie:

package C; / / C packages
import A.B.Cookie.*;

public class ChocolateChip extends Cookie{
    public void test(a){
        bite(); // protected method}}Copy the code

Comparing the package access example, if BITE had package access, it would obviously not be accessible across packages. If you make it protected, you can use it for all methods that inherit from cookies.

To help you visualize this (assuming all classes are public) :

(5) summary

These four access modifiers are basically a class that controls which code has access to its members. Code in other packages can’t just start out saying, “Hey, I’m Bob’s friend!” And then you want to see Bob’s protected, package access, and private members. The only way to gain access to a member is:

  1. Make a member ofpublic. So anyone, anywhere, can access it.
  2. Give members default package access without any access modifiers, and then place other classes in the same package. In this way, other classes can access the member.
  3. An inherited class can be accessedpublicMembers can also be accessedprotectedMember (but not accessibleprivateMembers). Only if two classes are in the same package can they access members with package access rights.
  4. Accessor and mutator methods (also known as “get/set” methods) are provided to read and change values.

5. Class-based access

Class – based access is the same as package – based access and public – based access.

package A;

public class x{
    // ...
}
Copy the code

package A;

class y{
    // ...
}
Copy the code

| flying veal 🎉 pay close attention to the public, get updates immediately

  • The blogger is a postgraduate student in Southeast University and runs a public account “Flying Veal” in her spare time. The account was opened for the first time on 2020/12/29. Focus on sharing computer basics (data structure + algorithm + computer network + database + operating system + Linux), Java basics and interview guide related original technical good articles. The purpose of this public account is to let you can quickly grasp the key knowledge, targeted. I hope you can support me and grow with veal 😃