Java面向对象(2)
封装
封装的意义:
1.提高程序安全性 保护数据
2.隐藏代码实现细节
3.统一接口
4.提高系统可维护性
package com.oop.Demo04;
// 类
public class Student {
// 属性私有 private:私有
// 名字
private String name;
// 学号
private int id;
// 性别
private char sex;
// 年龄
private int age;
/*
提供一些可以操作这个属性的方法
提供public 的 get,set方法
get 获得这个数据
set 给这个数据设置值
*/
// 快捷键 alt + insert 自动生成get,set方法
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;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 120 || age <0){// 不合法的
this.age = 3;
}else{
this.age = age;
}
}
// 学习()
public void study(){
System.out.println("Study English");
}
// 睡觉()
public void sleep(){
System.out.println("Sleep in the bed 呼呼呼");
}
}
运行代码:
package com.oop;
import com.oop.Demo04.Student;
/***
* ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
* ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
* ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
* ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
* ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
* ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
* ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
* ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
* ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
* ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
* ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
* 单身狗就这样默默地看着你,一句话也不说。
*/
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("Wu");
System.out.println(s1.getName());
s1.setId(23);
System.out.println(s1.getId());
s1.setAge(-4); // 不合法的
System.out.println(s1.getAge());
}
}