学习Java第十二天--面向对象三大特性之封装

8.面向对象三大特性

8.1 封装

8.1.1 封装的必要性

public class TestEncapsulation{
	public static void main(String[] args){
		Student s1 =new Student();
		s1.name = "tom";
		s2.age = 20000;//在对象外部,为对象属性赋值,可能存在非法数据的录入
		s1.sex = "male";
		s1.score = 100D;
	}
}					//就目前所学而言,并没有办法对属性的赋值加以控制
class Student{
	String name;
	int age;
	String sex;
	double score;
}

8.1.2 什么是封装

  • 概念:尽可能隐藏对象的内部实现细节,控制对象的修改及访问的权限;
  • 访问修饰符:private (可将属性修饰符为私有,仅本类可见)
public class TestEncapsulation{
	public static void main(String[] args){
		Student s1 = new Student();
		s1.age = 2000;//编译错误:私有属性在类的外部不可访问
	}
}
class Student{
	private int age;
}

8.1.3 公共访问方法

public class TestEncapsulation{
	public static void main(String[] args){
		Student s1 = new Student();
		s1.setAge(20000);	//以访问方法的形式,进而完成赋值与取值操作。
		System.out.println(s1.getAge());
	}
}
class Student{
	String name;
	private int age;
	String sex;
	double score;

	public void setAge(int age){	//提供公共访问方法,保证数据的正常录入
		this.age = age;
	}
	public int getAge(){
		return this.age;
	}
}
  • 命名规范:
    赋值:setXXX() //使用方法参数实现赋值
    取值:getXXX() //使用方法返回值实现取值

8.1.4 过滤有效数据

public class TestEncapsulation {

	public static void main(String[] args) {
		//
		Student s1 = new Student();
		s1.name = "tom";
				s1.sex = "男";
				s1.score = 100D;
		
				s1.setAge(45);
				System.out.println(s1.getAge());
	}

}
class Student{
	String name;
	private int age;
	String sex;
	double score;
	
	public Student() {}
	
	public void setAge(int age) {
		if(age > 0 && age < 253) {//指定有效范围
			this.age = age;
		}else {
					this.age = 18;//录入非法数据时的默认值
}
	}
	public int getAge() {
				return this.age;
	}
}
  • 公共的访问方法内部,添加逻辑判断,进而过滤掉非法数据,以保证数据安全;

8.1.5 小结

在这里插入图片描述

发布了34 篇原创文章 · 获赞 7 · 访问量 1305

猜你喜欢

转载自blog.csdn.net/weixin_44257082/article/details/104381587