把抽象出的数据(属性)和对数据的操作(方法)封装在一起,数据被保护在内部,程序的其他部分只有通过被授权的操作(方法),才能对数据进行操作。
好处:
1)隐藏实现细节
2)可以对数据进行验证,保证安全合理
实现步骤:
1)将属性进行私有化(不能直接修改属性)
2)提供一个公共(public)的 set 方法,用于对属性判断并赋值
public void setXxx(类型 参数名){ //Xxx表示某个属性
//加入数据验证的业务逻辑
属性 = 参数名;
}
3)提供一个公共(public)的 get 方法,用于获取属性的值
public 数据类型 getXxx(){ //权限判断,Xxx表示某个属性
return xx;
}
e.g. 1
package com.hspedu.encap;//声明该类在哪个包下
public class Encapsulation01{
public static void main(String[] args){
Person person = new Person();
person.setName("jack");
person.setAge(30);
person.setSalary(30000);
System.out.println(person.info());
}
}
class Person{
public String name; //名字公开
private int age; //年龄私有化
private double salary; //工资私有化
//构造器
public Person(){
}
public Person(String name, int age, double salary){
//this.name = name;
//this.age = age;
//this.salary = salary;
//使用以上方法在调用构造器时会导致年龄工资没法验证,所以需要使用下面的方法
//可以将set方法写在构造器中,这样仍然可以验证
setName(name);
setAge(age);
setSalary(salary);
//自己写get和set太慢,快捷键:alt + Insert -> getter and setter
//然后根据要求完善代码
//name
public void setName(String name){
//加入对数据的校验
if(name.length() >= 2 && name.length() <= 6){
this.name = name;
}else{
System.out.println("名字的长度不对,需要(2-6)字符,默认名字");
this.name = "无名人";
}
}
public String getName(){
return name;
}
//age
public void setAge(String age){
//判断
if(age >= 1 && age <= 120){ //如果是合理范围
this.age = age;
}else{
System.out.println("你设置的年龄不对,需要在1-120,默认年龄18");
this.age = 18; //给一个默认年龄
}
public String getAge(){
return age;
}
//salary
public void setSalary(String salary){
this.salary = salary;
}
public String getSalary(){
//可以在这里增加对前对象的权限判断
return salary;
}
//写一个方法返回属性信息
public String info(){
return "信息为 name = " + name + "age = " + age + "salary = " + salary;
}
}
可以通过无参构造器调用set,或者直接调用有参构造器



