封装
一、封装的概念
当我们创建一个类的对象以后,我们可以通过“对象.属性”的方式,对对象的属性进行赋值。这里,赋值操作要受到属性的数据类型和存储范围的制约。但是除此之外,没有其他制约条件。但是,在实际问题中,我们需要给属性赋值加入额外的限制条件。这个给条件就不能在属性声明时体体现,我们只能通过方法进行限制的添加。(比如下图的setLeags)。同时,我们需要避免用户再使用“对象.属性”的方法对属性进行赋值。则需要将属性声明为私有的(private)
此时,针对于属性就体现了封装性
二、封装的方法
我们将类的属性私有化(private),同时,提供公共的(public)方法来获取(get)和设置(set)属性的值。
三、封装性的体现,需要权限修饰符来配合。
1、Java规定的4中权限(从小到大),private 缺省 default protected public。
2、4中权限可以用来修饰类及类的内部结构,属性,方法,构造器,内部类。
3、具体的。4中权限都可以用来修饰类的内部结构,属性,方法,构造器,内部类。
修饰类的话,只能使用缺省,public
总结封装性: Java提供了4中权限修饰符来修饰类及类的内部结构,体现了类及类的内部结构在被调用时的可见性的大小
四、练习
封装实例——宠物结婚
本实例实现判断两个宠物是否可以结婚,运用Java面向对象特征的封装性,对类进行封装。
【技术要点】
实现宠物结婚的技术要点如下:
定义一个宠物,包括名称、年龄、性别、配偶等基本属性。结婚必须满足三个条件:必须是异性,同性不允许结婚;有配偶者不能结婚;要达到结婚年龄方可结婚:雄性满5岁,雌性满4岁。
注意对方法进行封装 在Pet类中将方法进行创建和封装,在Test测试类中直接创建对象,调用Pet中的方法
pet类
public class Pet {
private int age;
private String name;
private int sex; //1为男性 0为女性
private Pet spouse; //配偶
//添加有参构造方法
public Pet(String name,int age,int sex,Pet spouse) {
this.name = name;
this.age = age;
this.sex = sex;
this.spouse = spouse;
}
//添加Set 和 Get方法
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public Pet getSpouse() {
return spouse;
}
public void setSpouse(Pet spouse) {
this.spouse = spouse;
}
//添加年龄判断方法
public boolean isOverForMarry() {
if (this.sex == 1 && this.getAge() >= 5) { //雄性大于5岁
return true;
}
if (this.sex == 0 && this.getAge() >= 4) { //雌性大于4岁
return true;
}
return false;
}
public boolean marry(Pet pet) {
if (this.sex == pet.sex) {
System.out.println("不符合规定,不允许同性结婚");
return false;
}
if (this.spouse != null || pet.spouse != null) {
System.out.println("一方已经结婚");
return false;
}
if (!this.isOverForMarry() || !pet.isOverForMarry()) {
System.out.println("未到达结婚年龄");
return false;
}
System.out.println("恭喜"+this.name+"和"+pet.name+"结婚");
//结婚成功 身份信息绑定
this.spouse = pet;
pet.spouse = this;
return true;
}
}
测试类
public class Test {
public static void main(String[] args) {
//创建实例化对象
Pet pet1 = new Pet("Cat1",5,1,null);
Pet pet2 = new Pet("Cat2",4,0,null);
Pet pet3 = new Pet("Cat3",6,1,null);
Pet pet4 = new Pet("Cat4",5,1,null);
Pet pet5 = new Pet("Cat5",3,0,null);
//直接调用在Pet类中封装的方法
pet1.marry(pet2); //pet1能否和pet2结婚
pet2.marry(pet3); //pet2能否和pet3结婚
pet3.marry(pet4);
pet4.marry(pet5);
}
}
运行结果