8.面向对象三大特性
8.1 封装
8.1.1 封装的必要性
public class TestEncapsulation{
public static void main(String[] args){
Student s1 =new Student();
s1.name = "tom";
s2.age = 20000;
s1.sex = "male";
s1.score = 100D;
}
}
class Student{
String name;
int age;
String sex;
double score;
}
8.1.2 什么是封装
- 概念:尽可能隐藏对象的内部实现细节,控制对象的修改及访问的权限;
- 访问修饰符:private (可将属性修饰符为私有,仅本类可见)
public class TestEncapsulation{
public static void main(String[] args){
Student s1 = new Student();
s1.age = 2000;
}
}
class Student{
private int age;
}
8.1.3 公共访问方法
public class TestEncapsulation{
public static void main(String[] args){
Student s1 = new Student();
s1.setAge(20000);
System.out.println(s1.getAge());
}
}
class Student{
String name;
private int age;
String sex;
double score;
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
- 命名规范:
赋值:setXXX() //使用方法参数实现赋值
取值:getXXX() //使用方法返回值实现取值
8.1.4 过滤有效数据
public class TestEncapsulation {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "tom";
s1.sex = "男";
s1.score = 100D;
s1.setAge(45);
System.out.println(s1.getAge());
}
}
class Student{
String name;
private int age;
String sex;
double score;
public Student() {}
public void setAge(int age) {
if(age > 0 && age < 253) {
this.age = age;
}else {
this.age = 18;
}
}
public int getAge() {
return this.age;
}
}
- 公共的访问方法内部,添加逻辑判断,进而过滤掉非法数据,以保证数据安全;
8.1.5 小结