且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您能解释一下有关封装的问题吗?

更新时间:2023-11-10 08:04:52

public class Example {
  private int a;

  public int getOtherA(Example other) {
    return other.a;
  }
}

赞.如您所见,private不能保护实例成员不被另一个实例访问.

Like this. As you can see private doesn't protect the instance member from being accessed by another instance.

顺便说一句,只要您谨慎一点,这还不算很坏. 如果private不能像上面的示例那样工作,那么编写equals()和其他此类方法将很麻烦.

BTW, this is not all bad as long as you are a bit careful. If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.