gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:24:37 25 4
gpt4 key购买 nike

我在《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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com