封装式类的三大特征之一。
将类的状态信息隐藏。
封装的步骤:
修改属性的可见来限制对属性的访问。为每个属性创造一对赋值setter方法和取值getter方法,对属性进行存取。
封装的好处:
隐藏类的实现细节,让使用者只能通过程序员规定的方法来访问。方便加入存取控制语句,限制不合理。
以下为例:
/*
public:公开的,权限最大
protected: 子类和本类,如果是在另一个包中的子类,也可以用protected修饰的父类的内容
(default)默认情况:包权限
private:私有,只能在本类中使用
权限修饰符可以修饰类和方法和属性
*/
public class Cat
{
private String name;
private String sex;
private String strain;
private int health = 100;
private int hungry = 0;
private int love = 50;
public Cat (String name ,String sex ,String strain)
{
this.name = name;
this.sex = sex;
this.strain = strain;
}
public Cat(String name, String sex, String strain, int health, int hungry, int love){
this(name, sex, strain);
this.health = health;
this.hungry = hungry;
this.love = love;
}
public void setName(String name)
{
this.name =name;
}
public void setSex(String sex)
{
this.sex = sex;
}
public void setStrain(String strain)
{
this.strain = strain;
}
public void setHealth(int health)
{
if(health>100 || health <0)
{
this.health = 100;
System.out.println("健康值设置不合规定, 已调整为默认值" + this.health);
}else{
this.health = health;
}
}
public void setLove(int love)
{
this.love=love;
}//以上是赋值方法
public String getName(){
return name;
}
public String getSex()
{
return sex;
}
public String getStrain()
{
return strain;
}
public int getHealth()
{
return health;
}
public int getLove()
{
return love;
}
public void showInfo()
{
System.out.println("宠物的自白");
System.out.println("我的名字是:" + name + ",我的性别是:" + sex + ", 我的品种是: " + strain);
System.out.println("我的健康值:" + health + ",我的饥饿值是:" + hungry + ", 我的亲密度是: " + love);
}
public void play()
{
love += 10;
hungry += 5;
if (love >= 100)
{
System.out.println("生死不离如胶似漆");
love = 100;
}
if(hungry >= 80)
{
System.out.println("我快饿死了");
}
System.out.println(name+"好开心");
}
public void eat (String food)
{
System.out.println(name + "在开心的吃" + food);
hungry -=20;
if(hungry >= 100)
{
System.out.println("太饱了,喵~");
health = 100;
}
}
//以下代码是对private权限测试
private static void introduceSelf()
{
System.out.println("汪汪汪");
}
static void introduce()
{
Cat.introduceSelf();
System.out.println("喵喵喵");
}
}
接下来使用这个类的状态
class CatTest
{
public static void main(String [] args)
{
Cat a = new Cat("旺财","公","波斯猫");
a.showInfo();
a.setHealth(99);//使用setter方法改了健康值
a.showInfo();
a.eat("鱼");
a.play();
a.setName("萌萌");
System.out.println(a.getName());
System.out.println(a.getHealth());
a.showInfo();
a.introduce();
}
}