五(四)、封装性

面向对象的特征一:封装与隐藏;
  一、问题引入
    当我们创建一个类的对象以后,我们可以通过 “对象.属性”的方式,对对象属性进行赋值。
  这里,赋值操作要受到属性的数量类型和存储范围的制约。除此之外,没有其他制约条件,但是,在实际问题中,我们往往需要给属性赋值
  加入额外的限制条件。这个条件就不能在属性声明时体现,只能通过方法来限制条件的添加;
  同时,需要避免用户再使用“对象.属性”的方式对属性进行赋值;,则需要对属性添加private 权限修饰符
  此时,针对属性就是 封装性的体现;

例如:

 1 public class Day10Encapsulation4 {
 2     
 3     public static void main(String[] args) {
 4         Animal animal = new Animal();
 5         animal.name = "大黄"; 
 6         animal.age = 1;
 7         //animal.legs = 4;//private 不能直接调用,避免出错
 8         animal.setLegs(6);
 9         animal.show();
10         animal.setLegs(-6);
11         animal.show();
12                 
13                 
14     }
15 
16 }
17 class Animal{
18     String name;
19     int age;
20     private int legs;//腿的个数
21     
22     public void eat() {
23         System.out.println("进食");
24     }
25     
26     public void show() {
27         System.out.println("name = " +name+",age = "+age+",legs = " +legs);
28     }
29     
30     //对属性的设置
31     public void setLegs(int l) {
32         if(l>=0 && l%2 == 0) {
33             legs = l;
34         }else {
35             legs = 0;
36         }
37     }
38     //属性的获取
39     public int getLegs() {
40         return legs;
41     }
42 }

该例子就是,在设置 Animal的legs的时候,如果直接操作属性,很可能出现复数的情况,那么如果设置了 setLegs了那么可用避免 这种情况的发生;获取属性可以通过getLegs()获取;

  二、封装性的体现:
  我们将类的属性私有化,同时提供公共的方法来设置和获取此属性的值;
  拓展:封装性的体现,a.如上,b.private 方法 (不对外暴露的私有方法)
  三、封装性的体现需要权限修饰符的配合:
  1.java规定了4种权限修饰符:private 缺省 protected public;
  2.4种权限可以用来修饰类及类的内部结构:属性 方法 构造器 内部类
  3.4种权限可以用来修饰类的话,只能是 缺省 和 public

原文地址:https://www.cnblogs.com/lixiuming521125/p/13305175.html