目录
什么是封装?
-
方法就是一个封装
-
类也是一个封装
封装的优点:
-
提高功能的复用性
-
隐藏了实现细节,提高了安全性
举例:电脑类是一个封装(cpu,内存,硬盘,鼠标,键盘)学生类是一个封装(名字,年龄,性别)
访问修饰符
private:是私有的,只能在本类中访问(类访问权限)
缺省:只能在本包中访问(包访问权限)
protected:子类访问权限
public:在任何地方都可以访问
修饰符 | 类内部 | 同一个包 | 子类 | 任何地方 |
---|---|---|---|---|
private | √ | |||
缺省 | √ | √ | ||
protected | √ | √ | √ | |
public | √ | √ | √ | √ |
代码举例:
public class Student {
private String name;
private int age;
public void setAge(int a){
if(a<0){
System.out.println("非法输入");
}
else {
this.age = a;
}
}
public int getAge(){
return this.age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
-----------------------------------------------------------------------------------------
public class StudentTest {
public static void main(String[] args) {
Student student = new Student();
student.setAge(20);
System.out.println(student.getAge());
student.setName("CoderZjz");
System.out.println(student.getName());
}
}
-----------------------------------------------------------------------------------------
运行结果:
20
CoderZjz
this关键字
代表当前对象
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
注意:
-
静态的不能用this关键字,默认get不写this,底层给我们加上this
-
this关键字可以在构造器(构造方法)中使用
创作不易,如有帮助的话请点个赞吧!