java - 设置实例变量 public 并且不使用 setter 方法可能会破坏在 java 中使用我的类的协作者的代码?

标签 java

我在《Headfirst java》一书中找到了下面这段话。我不明白下面段落中的粗体部分。

Object: The point to setters (and getters, too) is that you can change your mind later, without breaking anybody else's code! Imagine if half the people in your com- pany used your class with public instance variables, and one day you suddenly realized, " Oops - there's something I didn't plan for with that value, I'm going to have to switch to a setter method." You break everyone's code. The cool thing about encapsulation is that you get to change your mind. And nobody gets hurt. The performance gains from using variables directly is so miniscule and would rarely be worth it.

最佳答案

该值的内部表示可能会发生变化,并需要使用新类型,可以使用 getter/setter 方法对其他代码隐藏该类型。

关于java - 设置实例变量 public 并且不使用 setter 方法可能会破坏在 java 中使用我的类的协作者的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60246133/

相关文章:

java - 无法将 @Stateless EJB 注入(inject) CDI bean(多模块)Jakarta EE 8

java - 如何模拟 DataSourceTransactionManager ?

java - 使用 Spring MVC 重新加载弹出页面

java - Android Retrofit2/RxJava2/Room——简单的数据处理

java - 在 Java 中更改图像分辨率而不调整大小

java - 如何使用 Java 从 XML 中读取值并将其保存在 Hashmap 中

java - 如何将OSGi连接到SAP?

java - 复制Postgres jdbc的正确使用方法

java - 任何简单的 Java REST 教程?

java - 将两个 HashMap 的值相乘