封装和隐藏

封装隐藏代码举例

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());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值