2014-04-05 123 views
1

我有diffuculties了解为什么我可以访问以外的私人字段。上下文? 为了澄清我添加了一个小MyClass的例子:Java的私人字段访问

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语言选择,或者是根本不可能的这个区别开来。上下文和(或多或少)传入的“同一类”等于(Object obj)方法?

非常感谢您提前!

回答

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 
    } 

} 
+0

好吧,我觉得我是那种对我的方式抓它。但是,再一次,像这样使用它是否是好习惯,还是最好和吸气剂和吸附剂一起使用? – baeda

+0

@baeda *真*取决于你的情况。使用getters允许子类覆盖非final的getter,并且在某些情况下是有用的。当有问题的值可能需要一些计算来获得时,吸气器也很有用。但是对于您的基本示例,使用该私有'int'似乎就足够了。一般而言,良好的做法是使用任何导致最清晰,最干净,最易维护的代码来满足您的要求。作为一个练习,尝试用getter和一个没有的版本写一个版本,并且看看哪一个更好。这是一个需要回答的重大问题。 –

+0

好的,会做的。感谢您的时间和答案! – baeda

0

其简单,你首先您收到的目的是MyClass类型

的cheking通过检查以下

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 

如果有你正在返回相同的属性值,它210其他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; 
    } 
0

是的,您可以在出现此访问的MyClass自身体内访问MyClass类型的引用的任何私有成员。

基于JLS 6.6.1的可存取(摘录):

引用类型的成员是 访问仅当类型是可访问的并且所述构件 被声明,以允许访问:

.......如果会员被宣布为私人会员,则只有当其发生在包含成员声明的顶级 类(第7.6节)的主体内时,才允许访问 。

希望帮助