为什么我可以访问“其他”的私有变量?直接对象,在我的equals(Object o)方法中 [英] Why can I access my private variables of the "other" object directly, in my equals(Object o) method

查看:86
本文介绍了为什么我可以访问“其他”的私有变量?直接对象,在我的equals(Object o)方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中的equals(Object o)方法中,我可以访问传入对象的私有变量,而无需通过其公共getter。

In Java in the equals(Object o) method I can access the private variables of the passed in object without going through its public getters.

public boolean equals(Object o){
    ...
    MyObject other = (MyObject)o;
    return getProp() == other.prop; 
}

怎么样?

推荐答案

私有数据可由该类的任何实例访问,即使A类的一个实例正在访问另一个A实例的私有成员也是如此。这很重要要记住,访问修饰符(私有,受保护,公共)控制访问,而不是实例访问。

Private data is accessible by any instance of that class, even if one instance of class A is accessing the private members of another instance of A. It's important to remember that that access modifiers (private, protected, public) are controlling class access, not instance access.

这篇关于为什么我可以访问“其他”的私有变量?直接对象,在我的equals(Object o)方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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