您能解释一下有关封装的问题吗? [英] Can you explain this thing about encapsulation?

查看:81
本文介绍了您能解释一下有关封装的问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

针对您最长时间保存的编程假设被证明是不正确的?问题,这是错误的假设之一原为:

In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:

私有成员变量是 私有给实例而不是私有 课.

That private member variables were private to the instance and not the class.

(我听不懂他在说什么,有人可以举一个例子来解释这是什么错误/正确吗?

I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?

推荐答案

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.

这篇关于您能解释一下有关封装的问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆