站长资讯网
最全最丰富的资讯网站

java中封装有什么作用?步骤是什么?

java中封装有什么作用?步骤是什么?

封装的作用:

(推荐教程:java入门教程)

(1)便于使用者正确使用系统,防止错误修改属性

(2)降低了构建大型系统的风险

(3)提高程序的可重用性

(4)降低程序之间的耦合度

封装的步骤:

(1)属性私有

(2)方法公开

(视频教程推荐:java视频教程)

代码举例:

package com.qfedu.test1;  public class Student { 	private  String name; 	private int age; 	private double score; 	 	public void setName(String name) { 		this.name = name; 	} 	public String getName() { 		return name; 	} 	 	public void  setAge(int age) { 		if(age > 0 && age <= 140) { 			this.age = age; 		}else { 			System.out.println("年龄不合适,使用默认年龄"); 			this.age = 18; 		} 	} 	 	public int getAge() { 		return age; 	} 	 	public void setScore(double score) { 		if(score >= 0 && score <= 100 ) { 			this.score = score; 		}else { 			System.out.println("分数不合适,使用默认分数"); 			this.score = 60; 		} 	} 	 	public double getScore() { 		return score; 	} 	 	public void printStu() { 		System.out.println("学生名字是" + name); 		System.out.println("学生分数是" + this.getScore()); 		System.out.println("学生的年龄是" + getAge()); 	} 	 	public static void main(String[] args) { 		Student stu1 = new Student(); 		stu1.name = "赵四"; 		stu1.age = -20; 		stu1.score = -50; 		// 以上代码 在实际开发中不会将测试类和实体类写在一起 	} }

赞(0)
分享到: 更多 (0)

网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号