gpt4 book ai didi

java - 在 getter/setter 中指定方法

转载 作者:行者123 更新时间:2023-12-01 23:48:17 25 4
gpt4 key购买 nike

要真正理解封装的含义,例如,类私有(private)字段必须通过类公共(public)方法访问是按照定义的,但实际上这没有什么区别,因为字段仍然可以按原样访问。
所以,我认为 getter/setter 内部应该有一些处理来隐藏字段的处理方式。但它打破了 pojos 背后的原则。如何处理这种情况?

最佳答案

我不确定你所说的“POJO 的原理”是什么。以下是一个 POJO,仍然隐藏了 getter 和 setter 后面的实现细节:

public class Example {
private int thousands;
private int units;

public void setValue(int value) {
thousands = value / 1000;
units = value % 1000;
}

public int getValue() {
return 1000 * thousands + units;
}
}

关于java - 在 getter/setter 中指定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16666931/

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