Java封装 [英] Java Encapsulation
问题描述
如果我们只是定义变量 private
并定义getter setter来访问这些变量,我们总是说数据将被封装。我的问题是,如果我们可以通过getter和setter访问变量(数据),数据是如何被隐藏或安全的?
We always say that data will be encapsulated if we simply define variables private
and define getters setters to access those variables. My question is if we can access the variables (data) though via getters and setters, how come data is hidden or safe?
我搜索了大量的解释但却一无所获。每个人只是在他们的博客和帖子中说它是一种数据隐藏技术,但没有解释/阐述它。
i googled a lot for explanation but find nothing. every one just said in their blogs and posts that it is a data hiding technique but has not explained/elaborated it.
期待在stackoverflow上获得适当的,令人满意的解释论坛。
looking forward to get appropriate, satisfactory explanation here at stackoverflow's forum.
推荐答案
我理解你的问题的方法是,虽然我们将变量声明为 private
,因为这些变量可以使用getter和setter访问,所以不是私有的。因此,这样做的意义是什么?
The way I understand your question is, although we declare variables as private
, as those variables can be accessed using getters and setters, the are not private. Therefore, what is the meaning of doing that?
好吧,当使用getter和setter时,你可以限制对 private的访问
变量。
Well, when using getters and setters, you can restrict access to the private
variables.
ie
private int x;
public int getInt(String password){
if(password.equals("RealPassword")){
return x;
}
}
同样适用于制定者。希望这有帮助!
And same for the setters. Hope this helps!
这篇关于Java封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!