[英]Why Can I Access Private Variable From Outside Class?
I was given the task to find out how to view but not edit a private int from another class.我的任务是找出如何查看但不编辑来自另一个 class 的私有 int。 I tried some overly complicated things, but what worked is this:我尝试了一些过于复杂的事情,但有效的是:
public int getC() {
return myC;
}
myC is a private int. myC 是一个私有整数。 Is it really this easy to give another class access to a private var?让另一个 class 访问私有变量真的这么容易吗? I thought they couldn't be shared.我以为他们不能分享。 Could someone explain why this is allowed?有人可以解释为什么允许这样做吗? Thanks.谢谢。
You created a public getter function to access the private variable.您创建了一个公共getter function 来访问私有变量。 So if another class has an instance of your class as its local variable, it can use the public function(getter) to access the private variable of your original class.因此,如果另一个 class 将您的 class 的实例作为其局部变量,它可以使用公共函数(getter)来访问原始 class 的私有变量。
The only way to expose private fields is through accessors
aka getters
.公开私有字段的唯一方法是通过accessors
又名getters
。
But you should follow 2 rules:但是你应该遵循两条规则:
Avoid the temptation to expose directly all your private fields via getters(ide shortcuts).避免通过 getter(ide 快捷方式)直接公开所有私有字段的诱惑。 Only add them if really needed.仅在确实需要时添加它们。
If the type you expose is not immutable take care of not escape references
by return defensive copies如果您公开的类型不是不可变的,请注意不要通过返回防御性副本来escape references
Exemple:示例:
private Date date;
public Date date() {
return date;
}
This code breaks encapsulation and it is the same as doing this.这段代码破坏了封装,它和这样做是一样的。
public Date date;
To solve this you have 2 solutions要解决这个问题,您有 2 个解决方案
public Date date() {
return new Date(date.getTime());
}
LocalDate
使用不可变版本的 Date -> LocalDate
Same logic applies for collection types.相同的逻辑适用于集合类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.