封装

封装

 

一:什么是封装:

  1.面向对象三大特征之一:封装

  2.封装概念:将类的某些信息隐藏在类内部,不予许外部程序直接访问,而是通过类提供方法来实现对隐藏信息对操作和访问

二.封装好处:

   a.只能通过规定方法访问数据b.隐藏类的实现细节c.方便加入控制语句d.方便修改实现

三:封装的步骤

   第一步:修改属性的可见性---->设为private

   第二步:创建公有的getter/setter方法---->用于属性的读写

   第三步:在getter/setter方法中加入属性---->对属性值得合法进行判断

四:封装:

    1.将属性私有化,访问修饰符设置为private,属性只能在本类使用

    2.在我们的类中给属性提供相对的get/set的方法,给外部的程序访问属性

    3.在属性的相对应的方法中,提供业务逻辑的判断

    4.在封装中如果属性设置业务逻辑的判断,在相对的构造方法中需要调用相对应的set方法

五:代码示范

public class Dog {

private String name;

private int health;

private int love;

private String type;

public Dog(){

}

public Dog(String name,int health,int love,String type){

 this.name=name;

 this.health=health;

 this.love=love;  

this.type=type;

 this.setHealth(health);  

}

public String getName(){  

return name;

}

public void setName(String name){  

this.name=name;

}

public int getHealth(){

 return health;

}

public void setHealth(int health){

 //对健康值做一个判断,只能在0~100之间

 if(health<0||health>100){  

 this.health=100;  

 System.out.println("输入的默认值不合法,设置为默认100");

 }else{

 this.health=health;

 }

}

public int getLove(){

 return love;

}

public void setLove(int love){

 if(love>=0&&love<=100){

 this.love=love;

}else{

  System.out.println("输入的亲密度不合法,请重新输入!");  

}

}

public String getType(){

 return type;

}

public void setType(String type){

 this.type=type;

}

public void show(){  

System.out.println("姓名:"+name+",健康值:"+health+",亲密度:"+love+",品种:"+type);

}

//测试类:

public static void main(String[] args) {

 Dog d=new Dog("旺财",1000,100,"中华田园犬");  

//d.setName("旺财");

 //d.setLove(100);  

//d.setHealth(100);

 //d.setType("中华田园犬");  

d.show();

}

}

原文地址:https://www.cnblogs.com/fxx0129-nn/p/6883373.html