私有成员变量是由同一个类的另一个对象访问的吗?

时间:2017-04-20 16:12:23

标签: java private-members

假设我们有这段代码:

A: <input type="number" onblur="fillB()" id="aRow">
B: <input type="number" onblur="fillA()" id="bRow">

显然在public class HelloWorld { public static void main(String[] args) { OtherClass myObject = new OtherClass(7); OtherClass yourObject = new OtherClass(4); System.out.print(myObject.compareTo(yourObject)); } } public class OtherClass { private int value; OtherClass(int value) { this.value = value; } public int compareTo(OtherClass c) { return this.value - c.value; } } 方法中,即使我在compareTo对象之外访问它,我也可以访问c.value?

1 个答案:

答案 0 :(得分:1)

您没有访问c对象之外的c.value。

您正在做的是在同一个班级中访问的私有变量。因为c变量与类的类型完全相同,所以可以访问该类中的私有变量c.value。

想象一下以下情况

public class HelloWorld 
{
    public static void main(String[] args)
    {
        OtherClass myObject = new OtherClass(7);
        OtherClass yourObject = new OtherClass(4);
        yourObject.value = 23;
        System.out.print(myObject.compareTo(yourObject));
    }
}

public class OtherClass
{
    private int value;
    OtherClass(int value) 
    {
        this.value = value; 
    }  

    public int compareTo(OtherClass c) 
    {
        return this.value - c.value;
    }  
}

您的代码无法编译,因为无法从OtherClass以外的任何类访问值。但是,如果您尝试访问c.value,那么您肯定会成功。

如果你更多地学习封装,你会更好理解,[官方文档](https://docs.oracle.com/javase/tutorial/java/concepts/object.html“Oracle Documentation”)是一个很好的信息来源。