Java面向对象07——封装
(补充 this关键字):
package oop.demon01.demon03;
/*
封装的意义:
1. 提高程序的安全性,保护代码
2. 隐藏代码的实现细节
3. 统一接口
4. 系统的可维护性增加了
快捷键:alt + insert
*/
public class Application {
public static void main(String[] args) {
Student s1= new Student();
// s1.name; private不可以直接调用(报错)----属性私有
s1.setName("wentaotao");
System.out.println(s1.getName());
s1.setAge(999);//不合法的
System.out.println(s1.getAge());
}
}
--------------------------------------------------------------------------------------------------------
package oop.demon01.demon03;
//类
public class Student {
//属性私有(属性私有时用private)
private String name;//名字 之前是public
private int id;//学号
private char sex;//性别
private int age;//年龄
//提供一些可以操作这个属性的方法!
//提供一些public1 的 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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>120 || age<0){//不合法
this.age=3;
}else{
this.age = age;
}
}
//学习()
//睡觉()
}
学习内容源自视频:b站狂神说Java