This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging

The article directories

  • The concept of encapsulation
  • Steps of encapsulation

The concept of encapsulation

The concept of encapsulation encapsulation is one of the three characteristics of object-oriented thinking. Encapsulation is to hide the implementation details and provide only external access interfaces. Implementation details are partially wrapped, hidden methods.

Benefits of encapsulation: Modularity, information hiding, code reuse, pluginization, easy debugging, and security

The disadvantages of encapsulation affect performance

Summary encapsulation can be thought of as a protective barrier that prevents the code and data of that class from being randomly accessed by code defined by an external class.

Access to the code and data of this class must be controlled through strict interfaces.

The main feature of encapsulation is that we can modify our own implementation code without having to modify the snippet that calls our code.

Proper encapsulation makes your code easier to understand and maintain, and it also makes your code more secure.

Steps of encapsulation

The following steps illustrate the benefits of proper encapsulation.

Usually if you want to pass information about a person you want to pass data field by field

void showPersonInfo(String name,int age){}Copy the code

It would be easier to design a Person class to pass data

class Person {
    String name;
    int age;
}

void showPersonInfo(Person person){}Copy the code

In order to keep the property values of a class under control, the properties should be protected with strict access rights

class Person {
    private String name;
    private int age;
}
Copy the code

Once properties are private, they are no longer accessible outside the class, so common methods for accessing the properties should be provided

class Person {
    private String name;
    private int age;

    public int getAge(a) {
        return age;
    }

    public String getName(a) {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

In the above instance, the public method is the entry point for the external class to access the class member variables. Normally, these methods are called getter and setter methods. The following example shows how variables from the Person class can be accessed:

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Errol");
        person.setAge(20);
        showPersonInfo(person);
    }

    static void showPersonInfo(Person person) {
        System.out.print("Name:" + person.getName() +
                " Age:"+ person.getAge()); }}Copy the code