在面向对象程式设计方法中,封装(Encapsulation)是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法。
也就是隐藏内部的实现细节,外部不能查看,通过提供对外的方法来调用与修改。
封装能让代码更易于理解与维护,同时也增强了代码的安全性。
private
关键字设置为私有属性,再设置公共的 get、set 方法方便外部取得、设置name的值。public class Student {
// 私有的名字变量
private String name;
// 取得名字的值
public String getName() {
return this.name;
}
// 设置名字的值
public void setName(String name) {
this.name = name;
}
}
封装还可以进行判断输入值是否合法,或者更多骚操作。
实例:
public class Student {
// 私有的名字变量
private String name;
// 私有的性别变量
private char sex;
// 取得名字的值
public String getName() {
return this.name;
}
// 设置名字的值
public void setName(String name) {
this.name = name;
}
// 取得sex
public char getSex() {
return sex;
}
// 设置sex过程中加入判断,防止输入不合法的值
public void setSex(char sex) {
if (sex == ‘男‘ || sex == ‘女‘) {
this.sex = sex;
}else {
System.out.println("输入不合法!");
}
}
}
调用:
import com.wnaoii.oop.Demo03.Student;
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.setName("小明");
System.out.println("名字叫:" + student.getName());
System.out.println("--------------");
// 输入值不合法
student.setSex(‘爬‘);
System.out.println(student.getSex());
// 输入值合法
student.setSex(‘男‘);
System.out.println("性别为:" + student.getSex());
}
}
结果:
名字叫:小明
--------------
输入不合法!
性别为:男
原文:https://www.cnblogs.com/WNAOII/p/14733601.html