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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment