Encapsulation在java中是将相关数据(变量)和功能(方法)绑定到一个称为类的单元中的过程。封装可以通过使用访问修饰符来实现,例如 public、private、protected 或 default,因此您的类将不会被其他人未经授权的访问,并且易于维护。
Encapsulation
我们可以创建完全封装的类
封装也被称为data hiding 因为您将变量设为私有,而变量只能通过公共 getter 和 setter 访问。
data hiding
java中的封装示例:
package com.arpit.java2blog; public class Employee{ private int employeeId; private String employeeName; private String department; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public static void main(String args[]) { Employee e1=new Employee(); e1.setEmployeeId(1); e1.setEmployeeName("John"); e1.setDepartment("Sales"); System.out.println("============="); System.out.println("Employee Id: "+e1.getEmployeeId()); System.out.println("Employee Name: "+e1.getEmployeeName()); System.out.println("Employee Department: "+e1.getDepartment()); } }
当你运行上面的程序时,你会得到下面的输出:
============= Employee Id: 1 Employee Name: John Employee Department: Sales
setAge(int age)
这就是java中的封装。
原文链接:https://codingdict.com/