1. 基本介绍
2. 封装介绍
3. 封装的理解和好处
4. 封装的实现步骤 (三步)
5. 快速入门案例
package com.xdr630.encap;
public class Encapsulation01 {
public static void main(String[] args) {
Person person = new Person();
person.setName("兮动人");
person.setAge(1000);
person.setSalary(30000);
System.out.println(person.info());
System.out.println(person.getSalary());
}
}
class Person {
public String name; //名字公开
private int age; //age 私有化
private double 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;
}
}
6. 将构造器和 setXxx 结合
- 在使用构造方法时,也同样可以验证,把 set 方法写到构造器中,在上面的基础上增加如下
//如果我们自己使用构造器指定属性
Person person1 = new Person("云兮动人", 200, 10000);
System.out.println("====兮动人的信息====");
System.out.println(person1.info());
//有三个属性的构造器
public Person(String name, int age, double salary) {
/* this.name = name;
this.age = age;
this.salary = salary;*/
//可以将 set 方法写在构造器当中,这样仍然可以验证
setName(name);
setAge(age);
setSalary(salary);
}
7. 练习
public class Account {
//为了封装,将3个属性设置为private
private String name;
private double balance;
private String pwd;
//提供两个构造器
public Account() {
}
public Account(String name, double balance, String pwd) {
this.setName(name);
this.setBalance(balance);
this.setPwd(pwd);
}
public String getName() {
return name;
}
//姓名(长度为2位3位或4位)
public void setName(String name) {
if (name.length() >= 2 && name.length() <= 4) {
this.name = name;
} else {
System.out.println("姓名要求(长度为2位3位或4位),默认值 无名");
this.name = "无名";
}
}
public double getBalance() {
return balance;
}
//余额(必须>20)
public void setBalance(double balance) {
if (balance > 20) {
this.balance = balance;
} else {
System.out.println("余额(必须>20) 默认为0");
}
}
public String getPwd() {
return pwd;
}
//密码(必须是六位)
public void setPwd(String pwd) {
if (pwd.length() == 6) {
this.pwd = pwd;
} else {
System.out.println("密码(必须是六位)默认密码为 000000");
this.pwd = "000000";
}
}
//显示账号信息
public void showInfo() {
//可以增加权限的校验
System.out.println("账号信息 name=" + name + " 余额=" + balance + " 密码" + pwd);
// if() {
// System.out.println("账号信息 name=" + name + " 余额=" + balance + " 密码");
// }else{
// System.out.println("你无权查看...");
// }
}
}
public class TestAccount {
public static void main(String[] args) {
//创建Account
Account account = new Account();
account.setName("jack");
account.setBalance(60);
account.setPwd("123456");
account.showInfo();
}
}