public class PrivateModifierTest {
private
String name = "Test String One";
private int cost = 100;
public static void main(String[] args) {
PrivateModifierTest pmt = new PrivateModifierTest();
System.out.println(pmt.name);
System.out.println(pmt.cost);
Test testClass = new Test();
testClass.test.name = "Test String Two";
testClass.test.cost = 500;
System.out.println(testClass.test.name);
System.out.println(testClass.test.cost);
}
}
class Test{
protected PrivateModifierTest test = new PrivateModifierTest();
/* public static void main(String[] args) {
PrivateModifierTest pmt = new PrivateModifierTest();
System.out.println(pmt.name);
System.out.println(pmt.cost);
Test testClass = new Test();
testClass.test.name = "Test String Two";
testClass.test.cost = 500;
System.out.println(testClass.test.name);
System.out.println(testClass.test.cost);
}*/
}
Now when i compile above program, it compiles well and gives output as :
Test String One
100
Test String Two
500
[Note : Above code is in single file called "PrivateModifierTest.java" ] Question 1 : Why does the program compile & run successfully. What i was thinking is, it should give error since i am accessing private variables through an instance. Also I am updating the values of private members through an instance of the class without using setter methods ??? Can anyone please explain as to why this thing happens ???
Question 2 : Now when i make Test Class as public and PrivateModifierTest Class as default and move the main() method to Test Class and rename the file to Test.java, Than the same code gives me compilation error, complaining about visibility of private members -- This is just as expected. Thus Question is why it is now giving compilation Error whereas, it was not giving earlier ???
Can anyone please explain as to why is such a behavior for private modifier in detail.
Thanks in Advance.
Saurabh