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());
}
}