One of the three characteristics — encapsulation

Package literally means package , Specialty is information hiding , Encapsulating data and data-based operations with abstract data types , Make it an indivisible and independent entity , Data is protected inside abstract data types , Hide interior details as much as possible , Only some external interfaces are reserved for external connection . Other objects of the system can only communicate and interact with the encapsulated object through authorized operations wrapped outside the data . In other words, the user does not need to know the details inside the object ( Of course, I don't know ), But the object can be accessed through the external interface provided by the object .

For packaging , An object encapsulates its own properties and methods , So it does not need to rely on other objects to complete its own operations .

There are three benefits to using encapsulation :

1、 Good packaging reduces coupling .

2、 The structure inside the class can be freely modified .

3、 More precise control over members .

4、 Hidden information , Implementation details .

First, let's look at two classes :Husband.java、Wife.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class Husband {
 
     /*
      * Encapsulation of attributes
      * A person's name 、 Gender 、 Age 、 The wife is the private property of this person
      */
     private String name ;
     private String sex ;
     private int age ;
     private Wife wife;
 
     /*
      * setter()、getter() Is the interface for external development of the object
      */
     public String getName() {
         return name;
     }
 
     public void setName(String name) {
         this .name = name;
     }
 
     public String getSex() {
         return sex;
     }
 
     public void setSex(String sex) {
         this .sex = sex;
     }
 
     public int getAge() {
         return age;
     }
 
     public void setAge( int age) {
         this .age = age;
     }
 
     public void setWife(Wife wife) {
         this .wife = wife;
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Wife {
     private String name;
     private int age;
     private String sex;
     private Husband husband;
 
     public String getName() {
         return name;
     }
 
     public void setName(String name) {
         this .name = name;
     }
 
     public String getSex() {
         return sex;
     }
 
     public void setSex(String sex) {
         this .sex = sex;
     }
 
     public void setAge( int age) {
         this .age = age;
     }
 
     public void setHusband(Husband husband) {
         this .husband = husband;
     }
 
     public Husband getHusband() {
         return husband;
     }
 
}

From the above two examples, we can see that Husband Inside wife Reference is not getter() Of , meanwhile wife Of age Also no getter() Methodical . As for the reason, I think you all know it , A man, a wife in a deep room , No woman wants to be known her age .

So encapsulation privatizes the properties of an object , At the same time, it provides some methods of properties that can be accessed by the outside world , If you don't want to be outside , We don't have to provide access . But if a class does not provide methods for external access , So this class doesn't make any sense . For example, we regard a house as an object , Beautiful decoration inside , Like sofa 、 TV play 、 Air conditioner 、 Tea table and so on are all private properties of the house , But if we don't have those walls , Is it possible for others to have a clear view ? No privacy ! There's the wall that's blocking it , We can have our own privacy, and we can change the decorations at will without affecting others . But if there are no doors and windows , A packed black box , What is the significance of existence ? So people can see the scenery through the doors and windows . So doors and windows are the interfaces for the external access of the house objects .

We can't really appreciate the benefits of encapsulation through this . Now let's analyze the benefits of encapsulation from a program perspective . If we don't use encapsulation , Then the object has no setter() and getter(), that Husband Class should write like this :

1
2
3
4
5
6
public class Husband {
     public String name ;
     public String sex ;
     public int age ;
     public Wife wife;
}

We should use it like this :

1
2
3
4
Husband husband = new Husband();
         husband.age = 30 ;
         husband.name = " Zhang San " ;
         husband.sex = " male " ;    // It seems a little redundant

But that day if we need to change Husband, For example age It is amended as follows String What about the type? ? You only have one place to use this class. OK , If you have dozens or even hundreds of such places , Are you going to break down . If encapsulation is used , We don't need to make any changes , Just a little change Husband Class setAge() The method can .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Husband {
 
     /*
      * Encapsulation of attributes
      * A person's name 、 Gender 、 Age 、 The wife is the private property of this person
      */
     private String name ;
     private String sex ;
     private String age ;    /* Change to String Type of */
     private Wife wife;
 
     public String getAge() {
         return age;
     }
 
     public void setAge(int age) {
         // Conversion can be
         this.age = String.valueOf(age);
     }
 
     /** Omitting other attributes setter、getter **/
 
}

Other places still quote that (husband.setAge(22)) remain unchanged .

Here we can see , Encapsulation does make it easy to modify the internal implementation of a class , Without modifying the customer code that uses this class .

We're looking at the benefits : More precise control of member variables .

Or that one? Husband, Generally speaking, when we refer to this object, it is not easy to make mistakes , But sometimes you're confused , It's written like this :

1
2
Husband husband = new Husband();
         husband.age = 300 ;

Maybe you wrote it carelessly , You found out it's okay , If we don't find out, it's a big problem , Approaching who has seen 300 Age old monster !

But with encapsulation, we can avoid this problem , We are right. age Control the access of (setter) Such as :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Husband {
 
     /*
      * Encapsulation of attributes
      * A person's name 、 Gender 、 Age 、 The wife is the private property of this person
      */
     private String name ;
     private String sex ;
     private int age ;    /* Change to String Type of */
     private Wife wife;
 
     public int getAge() {
         return age;
     }
 
     public void setAge(int age) {
         if(age > 120){
             System.out.println("ERROR:error age input....");    // Prompt error message
         }else{
             this.age = age;
         }
 
     }
 
     /** Omitting other attributes setter、getter **/
 
}

It's all right setter Method control , In fact, through the use of encapsulation, we can also control the export of objects very well . For example, gender in the database is generally already 1、0 Way to store , But we can't show it at the front desk 1、0, Here we just need to getter() Method, just do some conversion .

1
2
3
4
5
6
7
8
9
10
11
12
public String getSexName() {
         if ( "0" .equals(sex)){
             sexName = " Woman " ;
         }
         else if ( "1" .equals(sex)){
             sexName = " male " ;
         }
         else {
             sexName = " Simon? ???" ;
         }
         return sexName;
     }

When we use it, we only need to use it sexName To achieve the right gender display . The same can also be used to make different operations for different states .

1
2
3
4
5
6
7
8
9
public String getCzHTML(){
         if ( "1" .equals(zt)){
             czHTML = "<a href='javascript:void(0)' onclick='qy(" +id+ ")'> Enable </a>" ;
         }
         else {
             czHTML = "<a href='javascript:void(0)' onclick='jy(" +id+ ")'> Ban </a>" ;
         }
         return czHTML;
     }

Java Improve the understanding of the article java Three characteristics of —— More articles about encapsulation

  1. Java Improve the understanding of the article java Three characteristics of —— Inherit

    stay <Think in java> There is such a sentence in : Reuse code is Java One of the many compelling features . But to be a revolutionary language , It's not enough to just copy the code and change it , It has to be able to do more . In this sentence ...

  2. 【 turn 】java Improve ( Two )----- understand java The inheritance of the three characteristics of

    [ turn ]java Improve ( Two )----- understand java The inheritance of the three characteristics of Original address :http://www.cnblogs.com/chenssy/p/3354884.html stay <Think in ja ...

  3. java Improve ( Four )----- understand java The three characteristics of polymorphism

    There are three characteristics of object-oriented programming : encapsulation . Inherit . polymorphic . Encapsulation hides the internal implementation mechanism of classes , You can change the internal structure of a class without affecting its use , It also protects data . It's just to the outside world. Its internal details are hidden , What's exposed is its access method . Inherit ...

  4. java Improve ( Two )----- understand java The inheritance of the three characteristics of

    stay <Think in java> There is such a sentence in : Reuse code is Java One of the many compelling features . But to be a revolutionary language , It's not enough to just copy the code and change it , It has to be able to do more . In this sentence ...

  5. ( turn )java Improve ( Two )----- understand java The inheritance of the three characteristics of

    stay <Think in java> There is such a sentence in : Reuse code is Java One of the many compelling features . But to be a revolutionary language , It's not enough to just copy the code and change it , It has to be able to do more . In this sentence ...

  6. java Improve the understanding of the article java Three characteristics of —— polymorphic

    There are three characteristics of object-oriented programming : encapsulation . Inherit . polymorphic . Encapsulation hides the internal implementation mechanism of classes , You can change the internal structure of a class without affecting its use , It also protects data . It's just to the outside world. Its internal details are hidden , What's exposed is its access method . Inherit ...

  7. ( turn )java Improve ( Four )----- understand java The three characteristics of polymorphism

    There are three characteristics of object-oriented programming : encapsulation . Inherit . polymorphic . Encapsulation hides the internal implementation mechanism of classes , You can change the internal structure of a class without affecting its use , It also protects data . It's just to the outside world. Its internal details are hidden , What's exposed is its access method . Inherit ...

  8. java Improve ( One )----- understand java Encapsulation of three characteristics of

    From sophomore year java Start , It's almost three years now . From the most basic HTML.CSS To the last SSH I come out step by step , I had a good time . Lost . Lonely too . Although he is half a monk, he has accomplished it through his own efforts “ Studies ” ...

  9. ( turn )java Improve ( One )----- understand java Encapsulation of three characteristics of

    From sophomore year java Start , It's almost three years now . From the most basic HTML.CSS To the last SSH I come out step by step , I had a good time . Lost . Lonely too . Although he is half a monk, he has accomplished it through his own efforts “ Studies ” ...

Random recommendation

  1. ASP.NET Core Static documents and JS Package manager (npm, Bower) Use

    stay ASP.NET Core Add static files to although ASP.NET Mostly doing back-end things , But some static files on the front end are also very important . stay ASP.NET Core To enable static files in , need Microsoft.AspNe ...

  2. HPL/SQL And CDH5.4.7 Integrate

    1. download hplsql-0.3.13 Go local and unzip 2. modify plsql, As follows #!/bin/bash export "HADOOP_CLASSPATH=/opt/cloudera/parc ...

  3. Audio DAC analyse --- Untie HI-FI The secret of sound quality

    selected from :http://mp3.zol.com.cn/54/547689.html Whether we buy MP3.MP4 Good , In fact, the most commonly used function of our digital player is music playing , So the sound quality of the digital player , It's always been the consumer's ...

  4. ALV Header HTML Realization

    FORM frm_html_top_of_page USING cl_dd TYPE REF TO cl_dd_document. DATA: m_p TYPE i. DATA: m_buff TYP ...

  5. About C# Different digits are related to or , Or assignment , Hidden digit expansion should pay attention to

    __int64 a; char b; a = b; a |= b; As above , When b The highest position of 1 when , namely b=0x80( Or bigger ) when ,b It's expanding into 64 In the process, the highest position will be extended to the highest position and become 0xfffffffffffff ...

  6. HTML5 in canvas Signature panel with touch screen support

    1. Preface I've been too busy recently , From resigning after National Day , Looking for a job slowly , I have been working in this company for more than half a month , Too many sad tears to express , During the interview , I saw one company after another , Several companies left just after a day's work , Its ...

  7. Deploy windows service

    (1) cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319(2) InstallUtil.exe D:\SVN\zhongchao\ Development \WeiXin ...

  8. setInterval and setTimeout Call method knowledge

    function a() { alert('hello'); } setInterval(a, ); setInterval(a(), ); setInterval(); setInterval(); ...

  9. Learn with an example CSS Pseudo class elements of

    CSS Pseudo class elements are a very cool thing ! First of all, let's understand it ,:before :after Pseudo class elements , That's the false element . It can be inserted before or after the element , And in the HTML In the document structure , It doesn't exist , because Js It's impossible ...

  10. vim The use of some advanced commands in

    Now it's usually windows Following pair txt Document manipulation , I usually use gvim Software to operate , Although there is no unix/linu The following authentic , And many orders don't have , But there are many conveniences Here's a review vim On command , I myself used to ...