I am new to java... If I am missing something, please advise me.
I try to access the private method like below:
public class PublicClassPrivateMethodAndVariableAccess
{
private int a=23;
private void show()
{
System.out.println("a = "+a);
}
public static void main(String... arg)
{
PublicClassPrivateMethodAndVariableAccess pr = new PublicClassPrivateMethodAndVariableAccess();
System.out.println("using method showing pr.show() ");
pr.show();
System.out.println("pr.a = "+pr.a);
}
}
This will show output as:
using method showing pr.show()
a = 23
pr.a = 23
But when I’m using a similar code with a different way to access the private method...:
class Testclass
{
private int a=23;
private void show()
{
System.out.println("a = "+a);
}
}
public class NoModifierClassPrivateMethodAndVariableAccess
{
public static void main(String... arg)
{
Testclass pr = new Testclass();
System.out.println("using method showing pr.show() ");
pr.show();
System.out.println("pr.a = "+pr.a);
}
}
... it shows error as below:
NoModifierClassPrivateMethodAndVariableAccess.java:19: error: show() has private
access in Testclass
pr.show();
^
NoModifierClassPrivateMethodAndVariableAccess.java:20: error: a has private access in Testclass
System.out.println("pr.a = "+pr.a);
^
2 errors
I am asking why this second code is failing to access the private method?