Java的私有字段访问

时间:2014-04-05 19:56:31

标签: java

我有困难理解为什么我可以访问 this。上下文之外的私有字段? 为了澄清我添加了一个小的 MyClass示例:

public class MyClass {

    private int myPrivateInt;

    public MyClass(int myPrivateInt) {
        this.myPrivateInt = myPrivateInt;
    }

    public boolean equals(Object obj) {
        // if it's not an instance of MyClass it's obviously not equal
        if (!(obj instanceof MyClass)) return false;
        MyClass myClass = (MyClass) obj;

        // here comes the part I don't quite understand fully:
        // why can I access a private field outside of the "this." context?
        return this.myPrivateInt == myClass.myPrivateInt;
    }
}

这是一种delibarate语言选择还是根本无法区分 this。上下文和(或多或少)传递给 equals的“同一类”(对象obj)方法?

非常感谢你!

3 个答案:

答案 0 :(得分:3)

你错误地解释了private的含义。它不限制对this的访问,它限制了对MyClass任何代码的访问。因此MyClass中的任何内容都可以访问它,即使它来自MyClass的其他实例。

无法在MyClass之外访问它,例如:

public class MyClass {

    private int myPrivateInt;

    public void example (MyClass m) {
        int x = m.myPrivateInt; // <- OK, we are in MyClass 
    }        

}

public class SomewhereElse {

    public void example (MyClass m) {
        int x = m.myPrivateInt; // <- not allowed
    }

}

答案 1 :(得分:0)

很简单,你首先要知道你收到的对象是MyClass类型

通过检查以下

obj instanceof MyClass

然后如果是,则通过检查以下内容检查该对象是否具有与MyClass相同的属性值

this.myPrivateInt == myClass.myPrivateInt;//here you are not accessing it from outside but just comparing value of `MyClass` object property(`myPrivateInt`) to the `Object` you passed

如果它具有相同的属性值,则返回true其他false

所以这里一步一步地描述equals

public boolean equals(Object obj) {
        //you are cheking if the Object you passed is of MyClass type(means it is either MyClass object or any Child of MyClass)
        if (!(obj instanceof MyClass)) return false;
//if not return false directly, or just cast Object to MyClass(as you know it is MyClass type so it can be casted to MyClass and will not give any cast exception)
        MyClass myClass = (MyClass) obj;

        //here you are checking if the object you passed(which is supposed to contain properties MyClass has, so myClass object will also have myPrivateInt variable/property)
//you are just comparing that value to current MyClass object's myPrivateInt property
//if that also is equal, you can say both objects are equal
        return this.myPrivateInt == myClass.myPrivateInt;
    }

答案 2 :(得分:0)

是的,如果此访问权限发生在MyClass本身,您可以访问MyClass类型的引用的任何私有成员。

基于JLS 6.6.1 确定辅助功能(摘录):

  

引用类型的成员是   只有在可访问类型和成员时才可访问   声明允许访问:

     

.......如果该成员被宣布为私有,那么访问   当且仅当它出现在顶层的主体内时才被允许   包含成员声明的类(第7.6节)。

希望有所帮助