java封装
? 封装(Encapsulation)是面向对象方法的重要原则,就是把对象的属性和操作(或服务)结合为一个独立的整体,并尽可能隐藏对象的内部实现细节。
? 封装相当于一个保护屏障,不允许外部程序直接访问,可以将某些信息进行隐藏,只能通过类提供的方法对隐藏的信息进行操作访问。
? 优点:
? 减少耦合,方便修改和实现细节。
封装的步骤:
1.修改属性的可见性(private 私有的)
public class Person{
private String name;
Private int month;
}
注:将属性name和month设置为私有的后,只能本类才能访问,其他的类访问不了,这样就对信息进行了隐藏。
2.对每个值属性提供对外的公共方法访问,创建一对赋取值(set/get)方法,用于对私有属性的访问。
public class Person{
private String name;
Private int month;
public void setName(String name){
this.name=name;
}
public void setMonth(int month){
this.month=month;
}
public String getName(){
return this.name;
}
public int getMonth(){
return this.Month;
}
}

|