封装就是隐藏了实现细节,提高了安全性。
在一个类中有私有变量时,要想访问就需要提供get与set 方法例如:
/**
* 私有是封装的一种体现形式
* @author OWNER
*
*/
class Person{
private String name;
private int age;
public void setName (String name){
this.name = name;
}
public String getNname(){
return name;
}
public void setAge(int age){
if(age>0 && age<200){
this.age = age;
speak();
}
else{
System.out.println("Your age is wrong!");
}
}
public void speak(){
System.out.println(age+","+name);
}
public int getAge(){
return age;
}
}
public class PersonMain {
public static void main(String[] args){
Person p = new Person();
p.setAge(-10);
p.speak();
}
}