Java三大特性之封装

来源:互联网 发布:马云开淘宝怎么赚钱 编辑:程序博客网 时间:2024/06/05 02:48


学习Java,必须得了解Java的三大特性,今天就说说三大特性之一的封装。


封装就是把属性私有化,然后提供公共的方法来访问私有属性。


概念性的东西大家上网搜一下就行,下面我们分别举例说明封装的几个好处。


1.可以隐藏一些私有属性和一些实现过程。先看看封装前的代码:

public class TestClass {    public static void main(String[] str) {        Flower newFlower = new Flower();        newFlower.name = "JuHua";        newFlower.chanDi = "China";        newFlower.time = 10;        newFlower.xiShui = false;        Flower twoFlower = new Flower();        twoFlower.name = "GuiHua";        twoFlower.chanDi = "China";        twoFlower.time = 30        twoFlower.xiShui = false;    }}class Flower {    public String name;//花名    public int time;//最长花龄    public String chanDi;//产地    public boolean xiShui;//是否喜水}


再看看封装后的代码:

public class TestClass {    public static void main(String[] str) {        Flowers flowerSimple = new Flowers("JuHua", 10, "China", false);        Flowers flowerSimple2 = new Flowers("GuiHua", 30, "Juke", false);    }}class Flowers {    private String name;//花名    private int time;//最长花龄    private String chanDi;//产地    private boolean xiShui;//是否喜水    Flowers(String name, int time, String chanDi, boolean xiShui) {        this.name = name;        this.time = time;        this.chanDi = chanDi;        this.xiShui = xiShui;    }}

很明显,我们把类的属性给做了隐藏处理,然后使用公共的构造函数提供对外操作的入口,构造函数的实现过程也保持了对外的隐藏。


2.可以对赋值的属性进行一些代码处理,让代码逻辑更准确。 比如上面的例子中,封装前,对属性的初始化赋值是没有做任何兼容处理的,如果设置newFlower.time = 100000;程序不会报错,但是没有实际应用的意义了,所以也不能满足产品兼容性的要求,但是也没法进一步处理,而通过封装就可以很好的进行这种特殊处理。看代码:

public class TestClass {    public static void main(String[] str) {        Flowers flowerSimple = new Flowers("JuHua", 100000, "China", false);    }}class Flowers {    private String name;//花名    private int time;//最长花龄    private String chanDi;//产地    private boolean xiShui;//是否喜水    Flowers(String name, int time, String chanDi, boolean xiShui) {        this.name = name;        //对传入的参数进行合理性校验,如果是封装前,肯定做不到这个效果        if (time > 10000) {            System.out.println("The number is too big");        }        else        {            this.time = time;        }        this.chanDi = chanDi;        this.xiShui = xiShui;    }}

输出结果:

The number is too big


3.可以在需要修改时只改变封装函数即可。 还拿第一个例子来说,如果是封装前,我们需要把time的类型改成String,那么我们就需要在每个初始化的地方去修改初始化值为String类型,但是封装后则只需要做个简单处理即可,看代码:

class Flowers {    private String name;//花名    private String time;//最长花龄,换成String类型了    private String chanDi;//产地    private boolean xiShui;//是否喜水    Flowers(String name, int time, String chanDi, boolean xiShui) {        this.name = name;        //不修改任何实现,只是把传入的int通过String.valueof进行下类型转换即可        this.time = String.valueOf(time);        this.chanDi = chanDi;        this.xiShui = xiShui;    }}


最后再总结下封装的好处:

1.可以隐藏一些私有属性和一些实现过程;

2.可以对赋值的属性进行一些代码处理,让代码逻辑更准确;

3.可以在需要修改时只改变封装函数即可。



长按关注「我在编程」

多看 | 多想 | 多练

实践是检验真理的唯一标准


0 0