简体   繁体   中英

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. I tried some overly complicated things, but what worked is this:

public int getC() { 
return myC; 
 }

myC is a private int. Is it really this easy to give another class access to a private var? 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. 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.

The only way to expose private fields is through accessors aka getters .

But you should follow 2 rules:

  • Avoid the temptation to expose directly all your private fields via getters(ide shortcuts). Only add them if really needed.

  • If the type you expose is not immutable take care of not escape references by return defensive copies

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

  • Return a defensive copy of your date
public Date date() {
   return new Date(date.getTime());
}
  • Use immutable version of Date -> LocalDate

Same logic applies for collection types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM