java怎么封装封装
什么是封装? (What is Encapsulation?)
- Encapsulation is one of the ways to achieve abstraction in Object-oriented programming. 封装是在面向对象编程中实现抽象的方法之一。
- It’s one of the core concepts of OOPS paradigm. 这是OOPS范式的核心概念之一 。
- Encapsulation is the process of hiding Objects’ properties from the outer world and provides methods to access them. 封装是从外部世界隐藏对象属性的过程,并提供访问它们的方法。
- It’s the mechanism to bind together the data and the function that work on it. 这是将数据和对其起作用的功能绑定在一起的机制。
- Encapsulation hides the objects’ data, so it’s also called data-hiding. 封装会隐藏对象的数据,因此也称为数据隐藏 。
用Java封装 (Encapsulation in Java)
We can achieve encapsulation in Java by declaring all the class fields as private. Then provide the public getter and setter methods for them.
我们可以通过将所有类字段都声明为私有来实现Java封装。 然后为他们提供公共的getter和setter方法。
Here is a simple example of encapsulation in a Java class.
这是一个封装在Java类中的简单示例。
package com.journaldev.oops.encapsulation;
public class Data {
private int id;
private String value;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
封装的优势 (Advantages of Encapsulation)
- The encapsulated code is loosely coupled. We can change the class variable name without affecting the client programs.
private String name; public String getValue() { return name; } public void setValue(String value) { this.name = value; }
Yes, you can’t change the methods because it might break the client code. The best way would be to mark these methods as deprecated and provide the new getter-setter methods.
封装的代码是松散耦合的 。 我们可以更改类变量名称,而不会影响客户端程序。private String name; public String getValue() { return name; } public void setValue(String value) { this.name = value; }
是的,您不能更改方法,因为它可能会破坏客户端代码。 最好的方法是将这些方法标记为已弃用,并提供新的getter-setter方法。
- The caller doesn’t know what is happening inside the getter and setter methods. It makes our code more secure. We can add some validations in the getter-setter methods.
调用者不知道getter和setter方法内部正在发生什么。 它使我们的代码更安全 。 我们可以在getter-setter方法中添加一些验证。public void setId(int id) { if (id < 0) throw new IllegalArgumentException("id can't be negative."); this.id = id; }
- We can easily implement access control for the object properties. If you don't want some class variable to be set from outside, don't provide the setter method. 我们可以轻松地实现对对象属性的访问控制 。 如果您不想从外部设置某些类变量,请不要提供setter方法。
- The encapsulation helps in writing unit test cases easily. The unit testing frameworks provides ways to write test cases for the methods, not for the fields. 封装有助于轻松编写单元测试用例 。 单元测试框架提供了为方法而非领域编写测试用例的方法。
- The encapsulated code is reusable. If you didn't noticed, the above deprecated functions are using the new getter-setter methods. 封装的代码是可重用的 。 如果您没有注意到,以上不推荐使用的函数正在使用新的getter-setter方法。
参考资料 (References)
java怎么封装封装