封装
大部分时候是对于属性来的,对方法用的较少
好处:避免你去破环系统
重载 get set 一般不会使用重载 使用构造器多一些
/* 1.提高程序安全性,保护数据 * 2.隐藏代码的实现细节 * 3.统一接口 get set 实现规范 * 4.提高系统的可维护性 * */
package com.lf.oop;
import com.lf.oop.demo04.Student;
/* 1.提高程序安全性,保护数据
* 2.隐藏代码的实现细节
* 3.统一接口 get set 实现规范
* 4.提高系统的可维护性
* */
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("lf");
System.out.println(s1.getName());
s1.setAge(-1); //999 不合法的年龄
System.out.println(s1.getAge());
}
}
package com.lf.oop.demo04;
//类 private:私有
public class Student {
// 姓名 学号 性别 学习() 睡觉()
// 属性私有
private String name; //姓名
private int id; //学号
private char sex; //性别
private int age;
// 提供一些可以操作这些属性的方法!
// 提供一些public 的 get、set方法
// get 获得这个数据
public String getName(){
return this.name;
}
// set 给这个数据设置值
public void setName(String name){
this.name = name;
}
// alt + insert
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
// 重载 get set 一般不会使用重载 使用构造器多一些
public void setSex(char sex,int age) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age > 120 || age < 0){ //不合法的年龄
this.age = 3;
}else {
this.age = age;
}
}
}