java:封装的概念和代码

java:封装的概念和代码:

封装:将类的某些信息隐藏到类的内部,不允许外部程序直接访问,而是通过该类提供的方法来实现对隐藏信息的操作和访问

封装的好处:只能通过规定方法访问数据  隐藏类的实现细节  方便加入控制语句  方便修改实现

经过封装的属性,不能直接访问,需要通过公共属性get/set方法访问

代码:

package cnkgc.jredu.oop;
/**
 * 某公司要开发内部的“办公管理信息系统” 请使用面向对象的思想设计部门和员工信息
 * @author Vip宅男
 *
 */
public class Department {
/**
* 属性: 部门编号  部门名称
*/

public int depsno;//部门编号
public String depName;//部门名称
/**
* 封装
* @return
*/

public int getDepsno() {
return depsno;
}
public void setDepsno(int depsno) {
this.depsno = depsno;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
}

package cnkgc.jredu.oop;
/**
 * 
 * @author Vip宅男
 *
 */
public class Employees {
public char empSex;
public int empAge;
public String empdepName;//所在部门
public String empDuty;//职务
/**
* 封装
* @return
*/

public char getEmpSex() {
return empSex;
}
public void setEmpSex(char empSex) {
this.empSex = empSex;
}
public int getEmpAge() {
return empAge;
}
public void setEmpAge(int empAge) {
this.empAge = empAge;
}
public String getEmpdepName() {
return empdepName;
}
public void setEmpdepName(String empdepName) {
this.empdepName = empdepName;
}
public String getEmpDuty() {
return empDuty;
}
public void setEmpDuty(String empDuty) {
this.empDuty = empDuty;
}
public static void main(String[] args) {
Department dep=new Department();
Employees emp=new Employees();
//通过set属性传递数据
dep.setDepName("销售部");
emp.setEmpdepName("小王");
emp.setEmpAge(18);
emp.setEmpDuty("销售部经理");
//通过get属性得到数据
System.out.println("我是"+emp.getEmpdepName()+emp.getEmpAge()+"岁");
System.out.println("我的职位是"+dep.getDepName()+"的"+emp.getEmpDuty());
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值