Alternately, the following illustrates the concept as stated on
page 99 of the Java Language Specification ("if the member or
constructor is declared private, then access is only permitted
when it occurs from within the class in which it is declared"):
*****************************************************************
class OtherClass
{
private int otherClassInt_ = 1;
}
class SameClass
{
private int sameClassInt_;
SameClass(int sameClassInt)
{
sameClassInt_ = sameClassInt;
}
void showSameClassInt(SameClass sameClassInstance)
{
System.out.println(sameClassInstance.sameClassInt_);
}
//void showOtherClassInt(OtherClass otherClassInstance)
//{
// System.out.println(OtherClass.otherClassInt_);
//}
}
class test
{
public static void main(String[] args)
{
SameClass instance1 = new SameClass(1);
SameClass instance2 = new SameClass(2);
instance2.showSameClassInt(instance1); // DISPLAYS "1"
instance1.showSameClassInt(instance2); // DISPLAYS "2"
}
}
This example compiles and executes properly only if method
"showOtherClassInt" is commented out; if it is not commented out, then you receive the error message "otherClassInt_ has private access in OtherClass" upon compilation.