package day32; public class Person {private String name;private int age; public String getName() {return name;} public void setName(String name) {this.name = name;} public int getAge() {return age;} public void setAge(int age) {if (age>120 || age<0){this.age=0;}else this.age = age;} }
package day32; public class Application {public static void main(String[] args) {Person person = new Person();person.setName("xiaohong");person.setAge(10);Person person1 = new Person();person1.setName("xiaoming");person1.setAge(-2);System.out.println(person.getName()+" "+person.getAge());System.out.println(person1.getName()+" "+person1.getAge());} }
在代码中采用private属性进行封装 然后用get(),set()方法进行操作
封装的意义:
-
提高程序的安全性
-
隐藏代码的实现细节
-
统一接口,形成一个规范
-
系统的可维护性增加了