面向对象编程三大特征-封装
面向对象编程三大特征-封装
基本概念
封装(encapsulation)就是把抽象出的数据【属性】和对数据的操作(方法)封装在一起,数据被保护在内部,程序的其他部分只有通过被授权的操作(方法),才能对数据进行操作。
封装的理解和好处
- 隐藏实现细节 调用(传入参数)->方法
- 可以对数据进行验证,保证安全合理。
封装的实现步骤
-
将属性进行私有化private 【不能直接修改属性】
-
提供一个公共的(public)set方法,用于属性判断并赋值
public void setXxx(类型 参数名) { //Xxx 表示某个属性
//加入数据验证的业务逻辑
属性= 参数名;
}
-
提供一个公共的(public)get方法,用于获取属性的值
public 数据类型 getXxx() { //权限判断,Xxx 某个属性
return xx;
}
代码示例:
public class Encapsulation01 {
public static void main(String[] args) {
Person person = new Person();
person.setName("jackaaaaaa");
person.setAge(150);
person.setSalary(6400);
System.out.println(person.info());
}
}
class Person {
public String name; //名字公开
private int age; //age 私有化
private double salary; //...
//构造器 alt + insert
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);
}
public String getName() {
return 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 int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 1 && age <= 120) {
this.age = age;
} else {
System.out.println("年龄设置不对,年龄需要在1-120,给默认年龄18");
this.age = 18; //给一个默认年龄
}
}
public double getSalary() {
//可以增加对当前对象的权限判断
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
//写一个方法,返回属性信息
public String info() {
return "信息为 name=" + name + " age=" + age + " salary=" + salary;
}
}
运行示例:
名字设置不对,名字需要2-6个字符,给默认名字
年龄设置不对,年龄需要在1-120,给默认年龄18
信息为 name=无名人 age=18 salary=6400.0

浙公网安备 33010602011771号