目录
一.封装
1.封装的概念
封装是对一些属性和行为进行隐藏,例如财富,它是一个隐私,我不想让外面去看到。
2.封装的好处
1)控制属性的读写控制,数据的安全检查(提高安全性)
2)隐藏实现细节, 减少修改、扩展类时对外界组件的影响,增强易维护性
3)提高软件的可复用性
3.封装的步骤
1)用private修饰属性
2)每个属性添加set,get方法
可以在里面勾选允许修改的属性和可以选择只允许set还是只允许get或者两个都可以
3)在set,get方法中添加控制语句
4.案例
Account.java
package com.gongsi.cn.oa.work727.classroom.Test7;
import java.util.Scanner;
public class Acount {
private String no;
private String name;
private String phone;
private double money;
public Acount() {
super();
}
public Acount(String no, String name, String phone, double money) {
super();
this.no = no;
this.name = name;
this.phone = phone;
this.money = money;
}
public double getMoney() {
return money;
}
//在set里面设置控制语句,不能那么轻易的存钱
public void setMoney(double money) {
Scanner input = new Scanner(System.in);
//假设密码08051005
System.out.print("请输入您的密码:");
String password=input.next();
if ("08051005".equals(password)) {
this.money+=money;
}else {
System.out.println("密码错误!!!不能乱动!!");
}
}
public String getName() {
return name;
}
}
Test.java
package com.gongsi.cn.oa.work727.classroom.Test7;
//封装 GET SET 方法
public class Test {
public static void main(String[] args) {
Acount acount=new Acount("95","王锁","15108079966",999999);
acount.setMoney(999);
System.out.println(acount.getName()+"的全部身家是:"+acount.getMoney()+"元!");
}
}
输错密码时:
密码正确时:
二.访问控制符
1.修饰类只能是public 和 default
2.修饰属性和方法:4个修饰符都可以。
4.案例
test8包下:
XiuShiFu.java
package com.gongsi.cn.oa.work727.classroom.test8;
public class XiuShiFu {
public String publicTestLian="脸孔";
private String privateTestDiKu="底裤";
protected String protectedTestMoney="105.85";
String defaultTest="默认!";
//同一个类下:public √ private √ protected √ default √
public void show() {
System.out.println(publicTestLian);
System.out.println(privateTestDiKu);
System.out.println(protectedTestMoney);
System.out.println(defaultTest);
}
}
TestXiuShiFu.java
package com.gongsi.cn.oa.work727.classroom.test8;
//修饰符的权限范围
public class TestXiuShiFu {
public static void main(String[] args) {
XiuShiFu xiuShiFu =new XiuShiFu();
//同一个包下:public √ private × protected √ default √
System.out.println(xiuShiFu.publicTestLian);
System.out.println(xiuShiFu.protectedTestMoney);
System.out.println(xiuShiFu.defaultTest);
}
}
Test7包下:
ZiLei.java
package com.gongsi.cn.oa.work727.classroom.Test7;
import com.gongsi.cn.oa.work727.classroom.test8.XiuShiFu;
public class ZiLei extends XiuShiFu{
public void show() {
//不同包的子类下:public √ private × protected √ default ×
System.out.println(this.publicTestLian);
System.out.println(this.protectedTestMoney);
}
}
TestXiuShiFu.java
package com.gongsi.cn.oa.work727.classroom.Test7;
import com.gongsi.cn.oa.work727.classroom.test8.XiuShiFu;
public class TestXiuShiFu {
public static void main(String[] args) {
XiuShiFu xiuShiFu=new XiuShiFu();
//不同包的不是子类下:public √ private × protected × default ×
System.out.println(xiuShiFu.publicTestLian);
}
}
通过此代码可一一得以验证