java的封装
- 程序设计应追求高内聚低耦合。意为类的内部数据操作细节自己完成,不允许外部干涉,同时仅暴露少量方法外界使用。也即是属性私有.
- 封装主要针对属性而言,使用get/set方法区操作属性
- 封装的意义:
- 1.提高程序的安全性,保护数据。
- 2.隐藏代码的实现细节
- 3.统一接口,使用同一的方法调用。
- 4.提升系统的可维护性。
封装代码实例:
Student类:
public class Student {
//属性:姓名,性别,学号,学习(),睡觉()
private String name;
private int id;
private char sexual;
private int age;
//属性私有
//提供操作属性方法,即public的get\set方法。
//get 获取该数据
public String getName(){
return this.name;
}
//set 为属性设置值
public void setName(String name){
this.name=name;
}
//自动生成get,set方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getSexual() {
return sexual;
}
public void setSexual(char sexual) {
this.sexual = sexual;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age>0 && age<128){ //在提供的方法内设置数据检测
this.age = age;
}
else {
this.age = 3;
}
}
}
主类main方法:
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("kuang");
System.out.println(s1.getName());
s1.setAge(-5);//数据不合法
System.out.println(s1.getAge());
}
}```