封装——面向对象三大特性
高内聚低耦合
对类中的属性进行私有化
/*
使用修饰符private对属性进行私有化
*/
//对于私有属性需要提供get/set方法实现属性值获取以及修改
//alt+insert快捷键快速构建get/set方法
示例
package course.oopLesson.Demo03;
public class Application {
public static void main(String[] args) {
//创建对象
Student xiaoMing = new Student();
//通过set方法修改对象的私有属性
xiaoMing.setName("多弗朗明哥");
xiaoMing.setAge(27);
xiaoMing.setGender("男");
//直接调用类中的public方法
xiaoMing.print();
}
}
package course.oopLesson.Demo03;
public class Student {
//设置三个私有属性
/*
使用修饰符private对属性进行私有化
*/
private String name;
private int age;
private String gender;
//一般方法不需要私有化
public void print(){
System.out.println("姓名:"+name+"\n"+"年龄:"+age+"\n"+"性别:"+gender);
}
//对于私有属性需要提供get/set方法实现属性值获取以及修改
//alt+insert快捷键快速构建get/set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<0||age>120){
System.out.println("输入年龄不合法!");
}else{
this.age = age;
}
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}