面向对象特性一、封装(Encapsulation)
封装:是指隐藏对象的属性和实现细节,仅对外提供公共访问方式。
好处:
将变化隔离
便于使用
提高复用性
提高安全性
封装原则:
将不需要对外提供的内容都隐藏起来
把属性都隐藏,提供公共方法让其访问
例如:
class Person
{
private String name;
private String sex;
private int age;
public getName()
{
return name;
}
public setName(String name)
{
this.name=name;
}
public getSex()
{
return sex;
}
public setSex(String sex)
{
this.sex=sex;
}
public getAge()
{
return age;
}
public setAge(int age)
{
if(age>1 && age<200)
this.age=age;
}
}