封装详解
package oop.demo04; public class Student { private String name; private int id; private char sex; private int age; //提供一些可以操作这个属性的方法 //提供一些public的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 int getAge() { return age; } public void setAge(int age) { if(age>120||age<0){ this.age=3; } else{ this.age = age; } } }
package oop; import oop.demo04.Student; public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("xc"); System.out.println(s1.getName()); s1.setAge(999);//不合法的 System.out.println(s1.getAge()); } }
封装的意义:
1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.系统的可维护性增加了