封装的理解和使用
- 封装的概念:将类的某些信息(属性)隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法来实现对隐藏信息的操作和访问。
- 封装的两大原则:(1)把所有的属性藏起来。(2)把尽可能多的东西藏起来,对外提供便捷的接口。接口——(方法等)。通过该类提供的方法来实现对隐藏信息的操作和访问。
- 优点:(1)保证源代码信息安全。(2)用户使用接口更方便。
实现封装
- 1)修改属性的可见性,设为private(私有),防止别人错误的修改。
- 2)创建公有的getter/setter方法(方法公开),用于属性的读写
- 3)在getter/setter方法中加入属性控制语句,对属性值的合法性进行判断。
- setter:1.属性赋值。2.属性的操作(正确判断等)
- getter:属性取值
- setter和getter快捷键:alt+insert
封装的好处
- 便于使用者正确使用系统,防止错误修改属性
- 有助于系统之间的松耦合,提高系统独立性
- 提高软件的可重用性
- 降低了构建大型系统的风险
//宠物狗狗类
import java.sql.SQLOutput;
/*
* 宠物狗狗类
* */
public class Dog {
//1.隐藏属性(添加private)
//昵称,默认值是“无名氏”
private String name="无名氏";
//1.health属性不被用户访问到 2.程序编写过程中要能控制health的赋值--方法中
/*if(this.health<0||this.health>100){
System.out.println("请输入0-100的值!");
this.health=60;
}else{
this.health=health;
}*/
//健康值,默认值是100,健康值在0-100之间,小于60为不健康
private int health=100;
//亲密度
private int love=0;
//品种
private String strain="聪明的拉布拉多犬";
//2.添加属性的setter/getter方法(方法公开),并加入属性控制语句
//setter:1.属性赋值。2.属性的操作(正确判断等)
public void setHealth(int health){
if(health<0||health>100){
System.out.println("请输入0-100的值!");
this.health=60;
return;
}
this.health=health;
}
//getter:属性取值
public int getHealth(){
return this.health;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getLove() {
return this.love;
}
public void setLove(int love) {
if(love<0||love>100){
System.out.println("请输入0-100的值!");
this.love=60;
return;
}
this.love=love;
}
public String getStrain() {
return this.strain;
}
public void setStrain(String strain) {
this.strain = strain;
}
/*
* 输出狗狗的信息
* */
public void print(){
System.out.println("宠物的自白:\n我的名字叫"+this.name+",健康值为"+this.health+
",和主人的亲密度为"+this.love+",我是一只"+this.strain+"。");
/*if(this.health<0||this.health>100){
System.out.println("请输入0-100的值!");
this.health=60;
}else{
this.health=health;
}*/
}
}
//宠物测试类
public class TestPet {
public static void main(String[] args) {
Dog dog=new Dog();
/*dog.health=-1000;*/
dog.setHealth(-1000);
System.out.println(dog.getHealth());
/*伪代码
do{
dog.health=-1000;
System.out.println("请输入0-100之间的数值!");
}while(dog.health>0||dog.health<100);*/
/*dog.love=3;
dog.name="多多";
dog.strain="吉娃娃";*/
dog.setLove(-9);
dog.setName("多多");
dog.setStrain("吉娃娃");
dog.print();
}
}