I am coming from a C++ background, so I am used to the main
function not being able to access private data members of an instance.
However, the case with Java is different as main
is a part of the public class, and can thus access the private data.
Why is it that a static method is given access to private data even though it does not belong to the calling instance? Is there any way I can avoid this from happening?
Here's a little snippet to explain what I mean:
public class Main
{
private int x = 5;
public static void main(String[] args) {
Main ob = new Main();
System.out.println(ob.x);
}
}
I want x
to be inaccessible from main
and that I have to use an accessor method for the same.