Java Foundation 11 - Encapsulation (ideas, access rights, this)

1. What is encapsulation?

Encapsulation is one of the three major characteristics of object-oriented.

Hide the properties and implementation details of the object, and only provide public access to the outside world.

① Encapsulation is to regard the state and behavior of the object as a whole, and store the two in an independent module, such as a class

②Encapsulation is also information hiding. It hides information that does not need to be known to the outside world, hides the details of object function implementation as much as possible, exposes methods to the outside world, and ensures safe access to the outside world, such as methods

public  static  void SaveMan( int PhoneNumber,String name, int QQnumber,String Email,String wechant) {
     // When we add contacts, we need to pass in a lot of data and it is very long, which leads to the lengthy parameter list 
}
class LinkMan{
    int PhoneNumber;
    String name;
    int QQnumber;
    String Email;
    String wechant;
    // In this way, we encapsulate the contact information and encapsulate it into a class 
}

Second, why encapsulate it?

1. Let's first look at the following code

public class FengZhuang {
public static void main(String[] args) {
    Person p=new Person();
    p.name="asa";
    p.age =-17 ; 
         // The negative number is unreasonable when setting the age, you should judge whether the input value is normal
     // This value can be accessed and modified through the dot operator. The set data is not safe 
}

}
class Person{
    String name;
    int age;
}  

So how do we solve the above problems?

class Person{
    String name;
    // Set the age permission modifier as private, which can only be accessed in this class and cannot be accessed by the outside world.
    // Since we have set the age to be private and cannot be accessed by the outside world, how do we set its value?
    // We specifically provide age with a public method to access him, this is the Setter and Getter methods 
    private  int age;
     public  int getAge() {
         return age;
    }
    // We can access age through the set method, and filter the incoming data, which improves the security of the data 
    public  void setAge( int age) {
         if (age<0 ) {
            System.out.println( "age cannot be negative" );
             return ; // end the program 
        } else {
                 this .age = age;
        }
    }
}
public class FengZhuang {
public static void main(String[] args) {
    Person p=new Person();
    p.setAge(-18);
}

When we enter a negative age, the system will return us a prompt, prompting us that it cannot be a negative number, but we don't know how it returns the value, how to judge these details, we only know the result.

①Encapsulation improves the security of the code.

②Hide the implementation details and provide an accessible way to the outside world. Ease of use by the caller.

③ Improve the reusability of the code.

 3. Permission Access Modifier

Encapsulation makes some classes unable to see what is specifically done in some classes, so java provides access modifiers to allow a class to see what is exposed and what cannot be exposed.

There are four kinds of access modifiers in java, which are private, default is not written, protected is protected, and public is public.

Their access rights are as follows

 

public

protected

default

private

in the same category

In the same package (subclasses and unrelated classes)

 

Subclasses from different packages

 

 

Unrelated classes in different packages

 

 

 

Note: private can only be accessed in this class, and cannot be accessed directly after leaving this class. It can be accessed but not directly accessed in other classes. For example, the set and get methods in the above code are a kind of fields that indirectly access the private modifier. method

General fields are modified with the private modifier to meet the requirements of hiding and security.

2. So what modifier should be used in what situation?
From a scope point of view, public can use all cases. But not really all use public, so what modifiers should be used in the end?
1. Attributes are usually encapsulated with private
2. Methods are generally used public to be called
3. Methods that will be inherited by subclasses are usually protected
and then the principle of minimum scope.
Simply put, if you can use private, use private, if not, enlarge it Level, use package, if not, use protected, and finally use public. In this way, the data can be encapsulated as much as possible, and there is no need to expose it, so there is no need to expose it.

Four, this keyword

Now there is a bicycle, Xiaoyu and Xiaoying have been riding this bicycle for a while, Xiaoyu said, I am really heavy to ride this bike, then the current "I" that is the user of this bike is Xiaoyu, Xiaoying said, I It's okay to ride, so the current "me", that is, the user of this car, is Xiaoying. this is equivalent to the word me, which represents the current object.

class Person{
    String name;
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int n) {
        if(n<0) {
            System.out.println( "Age cannot be negative" );
             return ;
        } else {
 // What does n here specifically refer to? 
                age = n;
        }
    }
}

n refers to the age we want to pass in, when we replace it with age

class Person{
    String name;
    private int age;
    public int getAge() {
        System.out.println(age);
        return age;
        
    }
    public void setAge(int age) {
        if(age<0) {
            System.out.println( "Age cannot be negative" );
            System.out.println(age);
            return;
        }else {
            System.out.println(age);
                age = age;
                System.out.println(age);
        }
    }
}

We see the above output, which shows that the age in the get method gets the age in the member variable, and the default value is 0, because the program follows the principle of proximity.

How to solve it?

When a member variable and a local variable have the same name, the this keyword can be used to distinguish, whoever calls this function this refers to.

class Person{
    String name;
    private int age;
    public int getAge() {
        System.out.println(age);
        return age;
        
    }
    public void setAge(int age) {
        if(age<0) {
            System.out.println( "Age cannot be negative" );
            System.out.println(age);
            return ; // end the program 
        } else {
            System.out.println(age);
                this.age = age;
                System.out.println(age);
        }
    }
}
public static void main(String[] args) {
    Person p=new Person();
    p.setAge(18);
    System.out.println(p.getAge());
    Person p2=new Person();
    p2.setAge(20);
    System.out.println(p2.getAge());
}

The output of the program is as shown in the figure above. When the p object is called, this refers to the p object, and when p2 is called, this refers to the p2 object.

Isn't that the principle of proximity? Why does the get method here get the value we passed?

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324648526&siteId=291194637