search
HomeJavajavaTutorialJava Improvement Chapter (1)-----Understanding the Encapsulation of the Three Major Characteristics of Java

It has been almost three years since I came into contact with Java in my sophomore year. From the most basic HTML and CSS to the final SSH, I walked through it step by step. I was happy, disappointed, and lonely. Although he is a half-way monk, he has completed his "study" through his own efforts. During this period, I participated in training institutions, but I really didn’t like that kind of training method, so I gave up and chose self-study (poor I paid 6,000 yuan). Although self-study was a lot of pain, it was more fun, and the effort and gain were only You know it yourself. Huang Tian lived up to his hard work, but I am stupid. In the first semester of his senior year, he finally completed Java by himself (he took a detour and wasted half a year), and got a good job with it. Thank you very much!

Too much gossip! Coming to the topic, LZ has just finished reading the design pattern recently and has a lot of feelings. And in the process of working, I deeply feel that the foundation of Java is not solid enough. For example, I am not familiar with IO, I don’t understand garbage collection, polymorphism, reflection, and even the three most basic features confuse me! So I am determined to make up for my Java basics! Starting from the first lesson---Encapsulation!!!!!!

One of the three major characteristics---Encapsulation

Encapsulation literally means packaging, and the professional point is information hiding , refers to the use of abstract data types to encapsulate data and data-based operations to form an indivisible independent entity. The data is protected inside the abstract data type, hiding internal details as much as possible, and only retaining some external Interfaces allow it to communicate with the outside world. 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 great benefits to use packaging:

1. Good packaging can reduce coupling.

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

3. Members can be more precisely controlled.

4. Hide information and implement details.

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

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;  
    }  
}
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 the wife reference in Husband does not have a getter(). At the same time, Wife's age also has no getter() method. As for the reason, I think everyone knows 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 the private properties of the house. But if we don't have those walls to block it, will others be able to see it 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 the house object left to the outside world for access.

Through this we cannot 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:

public class Husband {  
    public String name ;  
    public String sex ;  
    public int age ;  
    public Wife wife;  
}

We should use it like this:

Husband husband = new Husband();  
husband.age = 30;  
husband.name = "张三";  
husband.sex = "男";    //貌似有点儿多余

But if that day We need to modify Husband, for example, what about changing age 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. }

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 **/

Other places still reference (husband.setAge(22)) unchanged.

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

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

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

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

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

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

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 **/  
      
}

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

public String getSexName() {  
        if("0".equals(sex)){  
            sexName = "女";  
        }  
        else if("1".equals(sex)){  
            sexName = "男";  
        }  
        else{  
            sexName = "人妖???";  
        }  
        return sexName;  
    }

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

public String getCzHTML(){  
        if("1".equals(zt)){  
            czHTML = "<a href=&#39;javascript:void(0)&#39; onclick=&#39;qy("+id+")&#39;>启用</a>";  
        }  
        else{  
            czHTML = "<a href=&#39;javascript:void(0)&#39; onclick=&#39;jy("+id+")&#39;>禁用</a>";  
        }  
        return czHTML;  
    }

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

以上就是 java提高篇(一)-----理解java的三大特性之封装的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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
集邦咨询:英伟达 Blackwell 平台产品带动台积电今年 CoWoS 产能提高 150%集邦咨询:英伟达 Blackwell 平台产品带动台积电今年 CoWoS 产能提高 150%Apr 17, 2024 pm 08:00 PM

本站4月17日消息,集邦咨询(TrendForce)近日发布报告,认为英伟达Blackwell新平台产品需求看涨,预估带动台积电2024年CoWoS封装总产能提升逾150%。英伟达Blackwell新平台产品包括B系列的GPU,以及整合英伟达自家GraceArmCPU的GB200加速卡等。集邦咨询确认为供应链当前非常看好GB200,预估2025年出货量有望超过百万片,在英伟达高端GPU中的占比达到40-50%。在英伟达计划下半年交付GB200以及B100等产品,但上游晶圆封装方面须进一步采用更复

AMD “Strix Halo” FP11 封装尺寸曝光:和英特尔 LGA1700 相当,比 Phoenix 大 60%AMD “Strix Halo” FP11 封装尺寸曝光:和英特尔 LGA1700 相当,比 Phoenix 大 60%Jul 18, 2024 am 02:04 AM

本站7月9日消息,AMDZen5架构“Strix”系列处理器会有两种封装方案,其中较小的StrixPoint将采用FP8封装,而StrixHalo将会采用FP11封装。图源:videocardz消息源@Olrak29_最新曝料称StrixHalo的FP11封装尺寸为37.5mm*45mm(1687平方毫米),和英特尔AlderLake、RaptorLakeCPU的LGA-1700封装尺寸相同。AMD最新的PhoenixAPU采用FP8封装方案,尺寸为25*40mm,这意味着StrixHalo的F

Vue中Axios封装及其常用方法介绍Vue中Axios封装及其常用方法介绍Jun 09, 2023 pm 04:13 PM

Vue中Axios封装及其常用方法介绍Axios是一款基于Promise实现的HTTP库,它的优点在于具有良好的可读性、易用性以及可扩展性。Vue作为一款流行的前端框架,也对Axios提供了全面支持。本文将介绍如何在Vue中进行Axios封装,并且介绍Axios常用的一些方法。一、Axios封装在开发过程中,我们常常需要对Axios进行一些自定义的封装,例如

PHP中的封装技术及应用PHP中的封装技术及应用Oct 12, 2023 pm 01:43 PM

PHP中的封装技术及应用封装是面向对象编程中的一个重要概念,它指的是将数据和对数据的操作封装在一起,以便提供对外部程序的统一访问接口。在PHP中,封装可以通过访问控制修饰符和类的定义来实现。本文将介绍PHP中的封装技术及其应用场景,并提供一些具体的代码示例。一、封装的访问控制修饰符在PHP中,封装主要通过访问控制修饰符来实现。PHP提供了三个访问控制修饰符,

C++ 函数如何通过封装代码来提高 GUI 开发的效率?C++ 函数如何通过封装代码来提高 GUI 开发的效率?Apr 25, 2024 pm 12:27 PM

通过封装代码,C++函数可以提高GUI开发效率:代码封装:函数将代码分组到独立单元,使代码易于理解和维护。可重用性:函数可创建通用功能供应用程序中重复使用,减少重复编写和错误。简洁代码:封装代码使主逻辑简洁,便于阅读和调试。

如何在Go语言中实现封装和继承如何在Go语言中实现封装和继承Jul 23, 2023 pm 08:17 PM

如何在Go语言中实现封装和继承封装和继承是面向对象编程中的两个重要概念,它们可以使代码更加模块化和可维护,同时也为代码的复用提供了便利。本文将介绍在Go语言中如何实现封装和继承,并提供相应的代码示例。封装封装是将数据和功能进行封装,隐藏实现的细节,只暴露必要的接口给外部使用。在Go语言中,封装是通过导出和非导出标识符来实现的。首字母大写的标识符可以被其他包访

PHP代码封装技巧:如何使用类和对象封装可重复使用的代码块PHP代码封装技巧:如何使用类和对象封装可重复使用的代码块Jul 29, 2023 pm 11:19 PM

PHP代码封装技巧:如何使用类和对象封装可重复使用的代码块摘要:在开发中,经常遇到需要重复使用的代码块。为了提高代码的可维护性和可重用性,我们可以使用类和对象的封装技巧来对这些代码块进行封装。本文将介绍如何使用类和对象封装可重复使用的代码块,并提供几个具体的代码示例。使用类和对象的封装优势使用类和对象的封装有以下几个优势:1.1提高代码的可维护性通过将重复

富士康打造 AI 一条龙服务,投资的夏普进军半导体先进封装:2026 投产、设计月产 2 万片晶圆富士康打造 AI 一条龙服务,投资的夏普进军半导体先进封装:2026 投产、设计月产 2 万片晶圆Jul 18, 2024 pm 02:17 PM

本站7月11日消息,经济日报今天(7月11日)报道,富士康集团已进军先进封装领域,重点布局时下主流的面板级扇出封装(FOPLP)半导体方案。1.继旗下群创光电(Innolux)之后,富士康集团投资的夏普(Sharp)也宣布进军日本面板级扇出式封装领域,预计将于2026年投产。富士康集团在AI领域本身就有足够的影响力,而补上先进封装短板之后让其可以提供“一条龙”服务,便于后续接受更多的AI产品订单。本站查询公开资料,富士康集团目前持有夏普10.5%的股权,该集团表示现阶段不会增持,也不会减持,将维

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment