Home  >  Article  >  Java  >  Detailed explanation of encapsulation examples of Java's three major features

Detailed explanation of encapsulation examples of Java's three major features

零下一度
零下一度Original
2017-06-25 10:31:391033browse

One of the three major characteristics---encapsulation

Encapsulation literally means packaging. The professional point is information hiding, which refers to the use of abstract data types to encapsulate data and data-based operations. To make it constitute an indivisible independent entity, the data is protected inside the abstract data type, hiding the internal details as much as possible, and only retaining some external interfaces to connect it with the outside. Other objects in the system can only communicate and interact with this encapsulated object through authorized operations wrapped outside the data. That is to say, the user does not need to know the internal details of the object (of course there is no way to know), but can access the object through the interface provided by the object.

For encapsulation, an object encapsulates its own properties and methods, so it can complete its own operations without relying on other objects.

There are three major benefits of using encapsulation:

1. Good encapsulation can reduce coupling.

2. The internal structure of the class can be modified freely.

3. Members can be more precisely controlled.

4. Hide information and implement details.

First, let’s look at two classes: Husband.Java, Wife.java

Detailed explanation of encapsulation examples of Javas three major features##
public class Husband {
    
    /*
     * 对属性的封装
     * 一个人的姓名、性别、年龄、妻子都是这个人的私有属性
     */
    private String name ;
    private String sex ;
    private int age ;
    private Wife wife;
    
    /*
     * setter()、getter()是该对象对外开发的接口
     */
    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;
    }
}
Detailed explanation of encapsulation examples of Javas three major features
Detailed explanation of encapsulation examples of Javas three major features##
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;
    }
    
}
Detailed explanation of encapsulation examples of Javas three major features
From the above two examples, we can see that the wife reference in Husband does not have a getter(), and the wife’s age does not have a getter() method. As for the reason, I think you all know it. Men hide their wives in deep houses, and no woman wants others to know her age.

So encapsulation privatizes the properties of an object and provides some methods for properties that can be accessed by the outside world. If we don’t want to be accessed by outside methods, we don’t have to provide methods for outside access. But if a class does not provide methods for external access, then this class is meaningless. For example, we regard a house as an object. The beautiful decorations inside, such as sofas, TV series, air conditioners, tea tables, etc., are all private properties of the house. But if we don’t have those walls to block them, will others be able to see them at a glance? What about nothing left? No privacy at all! With that shielding wall, we can have our own privacy and we can change the furnishings inside at will without affecting others. But if there are no doors or windows, what is the meaning of a tightly wrapped black box? Therefore, others can also see the scenery inside through the doors and windows. Therefore, doors and windows are the interfaces of house objects left to the outside world for access.

Through this we can’t really appreciate the benefits of encapsulation. Now we analyze the benefits of encapsulation from a program perspective. If we do not use encapsulation, then the object does not have setter() and getter(), then the Husband class should be written like this:

Detailed explanation of encapsulation examples of Javas three major features
public class Husband {
    public String name ;
    public String sex ;
    public int age ;
    public Wife wife;
}
Detailed explanation of encapsulation examples of Javas three major features
We should use it like this:

Husband husband = new Husband();
        husband.age = 30;
        husband.name = "张三";
        husband.sex = "男";    //貌似有点儿多余
But if we need to modify the Husband that day, for example, change age How about changing it to String type? It's okay that you only use this class in one place. If you have dozens or even hundreds of such places, will you change it to a crash? If encapsulation is used, we don't need to make any modifications. We only need to slightly change the setAge() method of the Husband class.

Detailed explanation of encapsulation examples of Javas three major features
public class Husband {
    
    /*
     * 对属性的封装
     * 一个人的姓名、性别、年龄、妻子都是这个人的私有属性
     */
    private String name ;
    private String sex ;
    private String age ;    /* 改成 String类型的*/
    private Wife wife;
    
    public String getAge() {
        return age;
    }
    
    public void setAge(int age) {
        //转换即可
        this.age = String.valueOf(age);
    }
    
    /** 省略其他属性的setter、getter **/
    
}
Detailed explanation of encapsulation examples of Javas three major features

      其他的地方依然那样引用(husband.setAge(22))保持不变。

      到了这里我们确实可以看出,封装确实可以使我们容易地修改类的内部实现,而无需修改使用了该类的客户代码。

      我们在看这个好处:可以对成员变量进行更精确的控制。

      还是那个Husband,一般来说我们在引用这个对象的时候是不容易出错的,但是有时你迷糊了,写成了这样:

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

      也许你是因为粗心写成了,你发现了还好,如果没有发现那就麻烦大了,逼近谁见过300岁的老妖怪啊!

      但是使用封装我们就可以避免这个问题,我们对age的访问入口做一些控制(setter)如:

Detailed explanation of encapsulation examples of Javas three major features
public class Husband {
    
    /*
     * 对属性的封装
     * 一个人的姓名、性别、年龄、妻子都是这个人的私有属性
     */
    private String name ;
    private String sex ;
    private int age ;    /* 改成 String类型的*/
    private Wife wife;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age > 120){
            System.out.println("ERROR:error age input....");    //提示錯誤信息
        }else{
            this.age = age;
        }
        
    }
    
    /** 省略其他属性的setter、getter **/
    
}
Detailed explanation of encapsulation examples of Javas three major features

      上面都是对setter方法的控制,其实通过使用封装我们也能够对对象的出口做出很好的控制。例如性别我们在数据库中一般都是已1、0方式来存储的,但是在前台我们又不能展示1、0,这里我们只需要在getter()方法里面做一些转换即可。

Detailed explanation of encapsulation examples of Javas three major features
public String getSexName() {
        if("0".equals(sex)){
            sexName = "女";
        }
        else if("1".equals(sex)){
            sexName = "男";
        }
        else{
            sexName = "人妖???";
        }
        return sexName;
    }
Detailed explanation of encapsulation examples of Javas three major features

      在使用的时候我们只需要使用sexName即可实现正确的性别显示。同理也可以用于针对不同的状态做出不同的操作。

Detailed explanation of encapsulation examples of Javas three major features
public String getCzHTML(){
        if("1".equals(zt)){
            czHTML = "<a>启用</a>";
        }
        else{
            czHTML = "<a>禁用</a>";
        }
        return czHTML;
    }
Detailed explanation of encapsulation examples of Javas three major features

      鄙人才疏学浅,只能领悟这么多了,如果文中有错误之处,望指正,鄙人不胜感激!

The above is the detailed content of Detailed explanation of encapsulation examples of Java's three major features. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn