简体   繁体   English

为什么我可以从 Class 外部访问私有变量?

[英]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 个解决方案

  • Return a defensive copy of your date返回您约会对象的防御性副本
public Date date() {
   return new Date(date.getTime());
}
  • Use immutable version of Date -> LocalDate使用不可变版本的 Date -> LocalDate

Same logic applies for collection types.相同的逻辑适用于集合类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我可以从 main 方法访问私有变量? - Why can I access a private variable from main method? 在这种情况下为什么可以访问私有变量? - Why can I access the private variable in this case? 如何获得对父类的私有变量的访问权限? - How can I gain access to a parent class's private variable? 我正在尝试从子类访问私有变量 - I'm trying to access a Private Variable from a sub class 为什么我可以访问封闭类引用的私有成员 - Why can I access the private members of an enclosing class reference 为什么我不能在声明方法之外访问本地类? - Why can't I access local class outside declaring method? 为什么在java中我必须将类名添加到静态变量之前才能从类外部访问它。 想了解编译器 - Why is it in java I have to prepend the class name to static variable to access it from outside the class. Looking to understand the compiler 为什么我不能从另一个类访问方法但可以访问变量? - Why can't i access method from another class but can access variable? 为什么可以通过这种方式访问​​私有变量时无法访问基类的私有字段 - Why I can not access private field of a base class when private variables can be accessed this way 如何从测试类中访问私有方法 - how can I access a private method from the test class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM