私有成员变量被同class的另一个对象访问?
private member variable is accessed by another object of same class?
假设我们有这样的代码:
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 即使我在 c
对象之外访问它?
您没有在 c 对象之外访问 c.value。
您正在做的是访问 中 class 的 私有变量 class。因为 c 变量与 class 的类型完全相同,所以您可以在 class.
中访问私有变量 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 外,无法从任何 class 访问值。但是,如果您尝试访问 c.value,您肯定会成功。
如果你多研究一下封装,你会更好地理解,并且一个很好的信息来源是[官方文档](https://docs.oracle.com/javase/tutorial/java/concepts/object.html"Oracle Documentation")
假设我们有这样的代码:
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 即使我在 c
对象之外访问它?
您没有在 c 对象之外访问 c.value。
您正在做的是访问 中 class 的 私有变量 class。因为 c 变量与 class 的类型完全相同,所以您可以在 class.
中访问私有变量 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 外,无法从任何 class 访问值。但是,如果您尝试访问 c.value,您肯定会成功。
如果你多研究一下封装,你会更好地理解,并且一个很好的信息来源是[官方文档](https://docs.oracle.com/javase/tutorial/java/concepts/object.html"Oracle Documentation")