encapsulation
In the object-oriented programming method, Encapsulation refers to a method of packaging and hiding the implementation details of abstract functional interfaces.
- Encapsulation can be thought of as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by the outer class
- reflection mechanism
- Access to the code and data of this class must be controlled through a strict interface.
- The main function of encapsulation is to be able to modify its own implementation code without modifying the program fragments that call the code
- Proper packaging can make the code easier to understand and maintain, and also enhance the security of the code.
//第一步是确定研究的目标对象---可以区分的独立个体
// 需要方法和属性
class Student {
//成员属性---静态特征的描述
private boolean sex; //一般使用私有属性,共有的get/set方法
//成员方法---提供的功能描述
public boolean getSex(){
return this.sex;
}
//不允许修改sex,所以不提供set方法
protected void setSex(Boolean sex){
//如果在特殊情况下允许修改,可以使用范围限
定词进行表示
this.sex=sex;
}
}
//构建对象
Student s1=new Student();
s1.setSex(true);
s1.setSex(false); //是否允许取绝于限制
Encapsulation has three major benefits
- Good packaging reduces coupling
- The structure inside the class can be freely modified
- Allows for more precise control over members
- Hide information, implement details
4 keywords
for access control
//一个文件种可以定义无数个类,但是只能有一个public class公共类
public class Student {
//类的范围限定词分为2种情况。外部类的范围限定词可以使用无范围 限定词和public两种;而内部类上可以使用4种范围限定
//成员属性,类种包含哪些静态特征取决于问题本身
private Long id; //private只能在当前类中直接访问
protected String name; //protected可以在同包或者子类中直接访问
int age;//没有范围限定词,默认或者package限定词,只能在同包中直接访问
public double salary;//public到处可见
//一般规则是私有属性,共有的get/set方法
}
Memory method
Class definition rules: require high cohesion within the class and weak coupling between classes
- Encapsulation does make it easy to modify the internal implementation of a class without modifying the client code that uses it