Java Core Technology Chapter 4 - 1. Encapsulation

Encapsulation (sometimes called data hiding). The key to implementing encapsulation is that methods in a class must not directly access the instance field values ​​of other classes. Programs interact with an object's data only through the object's methods. Objects are given "black box" characteristics, improving reusability and reliability. In short, you only need to know the corresponding function of the method, without knowing its specific implementation process.

 

 

instance domain

  1. Private data fields:

    Private data fields are private variables or constants written globally. Private data fields are more complicated than public data fields because of the need to add field accessor and field mutator methods corresponding to private data fields, but they have the following obvious benefits:

    1. 1 Modifying the implementation in the method of this class will not affect other codes, such as modifying the return value of getBrithday and modifying its internal implementation.  

      

      2.1 If an exception occurs, the mutator method (ie, the set method) can perform error checking (debug). If the public data field can be directly assigned, then there may be many places where the error occurs.

 

  2. Public accessor and mutator methods:

    The accessor access is the get method, and the mutator method is the set method. A note here: try not to return accessor methods that reference mutable objects. can not read it? Look at the picture below:

      

    Because there is a setTime method in the Date type, if you directly return the reference object, and then use setTime to modify its object, it will destroy the encapsulation. Instead, the clone method of Object should be used to copy the data field, as shown below

      

    When you want to modify the brithday in UserInfo, you can call its corresponding mutator method (setBrithday).

 

    If there is something wrong or supplementary explanation, you can send an email to the blogger QQ mailbox: [email protected] or leave a message. thank you all.

 

 

  

 

Guess you like

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