Home >Java >Javagetting Started >What is the role of encapsulation in java? What are the steps?

What is the role of encapsulation in java? What are the steps?

王林
王林forward
2020-08-01 17:03:184055browse

What is the role of encapsulation in java? What are the steps?

The role of encapsulation:

(Recommended tutorial: java introductory tutorial)

(1) Convenient for users to use correctly system to prevent incorrect modification of attributes

(2) Reduce the risk of building large systems

(3) Improve the reusability of programs

(4) Reduce the differences between programs Degree of coupling

Encapsulation steps:

(1) Attribute private

(2) Method public

(Video tutorial recommendation: java Video tutorial)

Code example:

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;
		// 以上代码 在实际开发中不会将测试类和实体类写在一起
	}
}

The above is the detailed content of What is the role of encapsulation in java? What are the steps?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete