Suppose we have this code:
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;
}
}
apparently In the compareTo
method, I am able to access c.value even when i am accessing it outside of the c
object?
you are not accessing c.value outside of the c object.
What you are doing is accessing a private variable of a class in the same class. Because the c variable is of exactly the same type as the class, you can access private variable c.value in that class.
Imagine the following situation
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;
}
}
Your code would not compile because value is not accessible from any class other than OtherClass. However, if you try to access c.value you will certainly succeed in doing that.
You would understand better if you study encapsulation more, and a good source of information is the [official documentation](https://docs.oracle.com/javase/tutorial/java/concepts/object.html"Oracle Documentation")