打包性

封装性

本章目标
掌握封装的产生目的
掌握封装的实现
掌握setter和getter方法的定义

 

为什么要有封装

class Person{
	String name;//声明姓名属性
	int age;//声明年龄属性
	public void tell(){//取得信息的方法
		System.out.println("姓名:"+name+",  年龄:"+age);
	}
}
public class EncDemo01 {
	public static void main(String[] args) {
		Person per = new Person();//声明并实例化对象
		per.name = "张三";//为 name 属性赋值
		per.age = -30;//为 age 属性赋值
		per.tell();//调用方法
	}
/*结果:
 * 姓名:张三,  年龄:-30
 * */
}

 

 封装的实现
为属性封装:private 属性类型 属性名称 ;
为方法封装:private 方法返回值 方法名称(参数列表){}

class Person{
	private String name;//声明姓名属性
	private int age;//声明年龄属性
	public void tell(){//取得信息的方法
		System.out.println("姓名:"+name+",  年龄:"+age);
	}
}
public class EncDemo02 {
	public static void main(String[] args) {
		Person per = new Person();
		per.name = "张三";//错误,无法访问封装属性
		per.age = -30;//错误,无法访问封装属性
		per.tell();
	}
/*结果:
 * Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
 * The field Person.name is not visible //错误,无法访问封装属性
 * The field Person.age is not visible //错误,无法访问封装属性
 * at J020503.EncDemo02.main(EncDemo02.java:13)
 * */
}

 

setter及getter

class Person{
	private String name;//声明姓名属性
	private int age;//声明年龄属性
	public void tell(){//取得信息的方法
		System.out.println("姓名:"+name+",  年龄:"+age);
	}
	public String getName() {//取得姓名
		return name;
	}
	public void setName(String name) {//设置姓名
		this.name = name;
	}
	public int getAge() {//取得年龄
		return age;
	}
	public void setAge(int age) {//设置年龄
		this.age = age;
	}
}
public class EncDemo03 {
	public static void main(String[] args) {
		Person per = new Person();//声明并实例化对象
		per.setName("张三") ;//调用 setter 设置姓名
		per.setAge(-30);////调用 setter 设置年龄
		per.tell();//输出信息
	}
/*结果:
 * 姓名:张三,  年龄:-30
 * */
}

 

 加入验证

class Person{
	private String name;//声明姓名属性
	private int age;//声明年龄属性
	public void tell(){//取得信息的方法
		System.out.println("姓名:"+getName()+",  年龄:"+getAge());
	}
	public String getName() {//取得姓名
		return name;
	}
	public void setName(String name) {//设置姓名
		this.name = name;
	}
	public int getAge() {//取得年龄
		return age;
	}
	public void setAge(int age) {//设置年龄
		if(age >=0 && age<=150){//在此处加上验证代码
			this.age = age;
		}
	}
}
public class EncDemo04 {
	public static void main(String[] args) {
		Person per = new Person();//声明并实例化对象
		per.setName("张三") ;//调用 setter 设置姓名
		per.setAge(-30);////调用 setter 设置年龄
		per.tell();//输出信息
	}
/*结果:
 * 姓名:张三,  年龄:0
 * */
}

 

封装的类图表示
打包性