面向对象特征之一:封装和隐藏
public class Person { // public int age;//像这种情况,是把类的属性开发出来,让调用者随意使用,这样会有问题 //我们需要对这样不能让调用者随意使用的属性做封装和隐藏 private int age; public void printAge(){ System.out.println("年龄是:" + age); } public int getAge(){ return age; } public void setAge(int a){ if(a <= 130 && a >= 0){ age = a; }else{ System.out.println("输入的年龄:" + a + " 不在0到150之间"); } } }
使用者对类内部定义的属性(对象的成员变量)的直接操作会导致数据的错误、混乱或安全性问题。
public class Animal { public int legs; public void eat(){ System.out.println(“Eating.”); } public void move(){ System.out.println(“Moving.”); } } //应该将legs属性保护起来,防止乱用。 保护的方式:信息隐藏 public class Zoo{ public static void main(String args[]){ Animal xb=new Animal(); xb.legs=4; System.out.println(xb.legs); xb.eat();xb.move(); } }
*信息的封装和隐藏
*
Java中通过将数据声明为私有的(private),再提供公共的(public)方法:getXxx()和setXxx()实现对该属性的操作,以实现下述目的:
隐藏一个类中不需要对外提供的实现细节;
使用者只能通过事先定制好的方法来访问数据,可以方便地加入控制逻辑,限制对属性的不合理操作;
便于修改,增强代码的可维护性;
public class Animal{ private int legs;//将属性legs定义为private,只能被Animal类内部访问 public void setLegs(int i){ //在这里定义方法 eat() 和 move() if (i != 0 && i != 2 && i != 4){ System.out.println("Wrong number of legs!"); return; } legs=i; } public int getLegs(){ return legs; } } public class Zoo{ public static void main(String args[]){ Animal xb=new Animal(); xb.setLegs(4); //xb.setLegs(-1000); xb.legs=-1000; //非法 System.out.println(xb.getLegs()); } }