封装隐藏代码举例
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 >= 0 && a <= 150){
age=a;
}else{
System.out.println("输入的年龄:"+a+"不在0到150之间");
}
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person();
// p.age = -100;//这样的情况,程序是对的,能执行,但不符合正常逻辑
// 像这种情况,是把类的属性开放出来,让调用者随意使用,这样会有问题
p.setAge(12);
p.printage();
}
}
信息的封装和隐藏
先把属性设置声明为私有的,用private关键字,通过编写public类型的设置属性和获取属性,比如对age去写get和set的方法,那么方法名就是setAge和getAge
Java中通过将数据声明为私有的(private),再提供公共(public)方法:getXxx()和setXxx()实现对该属性的操作,以实现下述目的:
隐藏一个类中不需要对外提供的实现细节;
使用者只能通过事先定制好的方法来访问数据,可以方便地加入控制逻辑,限制对属性的不合理操作;
便于修改,增强代码的可维护性;
代码练习
public class Animal {
public int legs;
public void eat() {
System.out.println("Eating");
}
public void move() {
System.out.println("moving");
}
}
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();
}
}
应该将legs属性保护起来,防止乱用。
保护的方式:信息隐藏
public class Animal {
private int legs;
public void setLegs(int i) {
if (i != 0 && i != 2 && i != 4) {
System.out.println("Wrong numbers of legs!");
return;
}
legs = i;
}
public int getLegs() {
return legs;
}
public void eat() {
System.out.println("Eating");
}
public void move() {
System.out.println("moving");
}
}
public class Zoo {
public static void main(String[] args) {
Animal xb = new Animal();
xb.setLegs(4);
xb.eat();
xb.move();
System.out.println(xb.getLegs());
}
}