1

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.

Priyanshul Govil
  • 518
  • 5
  • 20
  • 6
    You can move the `main` method to a class with no state which only purpose is to start the program – Joakim Danielson Feb 15 '21 at 08:22
  • 2
    Closely related: [How is this private variable accessible?](https://stackoverflow.com/questions/27482579/how-is-this-private-variable-accessible) – Ivar Feb 15 '21 at 08:26
  • 2
    Java is not c++. Trying to judge java by the standards of c++ will lead you into trouble. The reverse is also true. – NomadMaker Feb 15 '21 at 08:49

1 Answers1

3

There is no way to protect "a class from itself". Private means that the current class (and only the current class) can access the field.

If you had a private field that no method could access, you could never read or update its value and thus render it unneccessary. By declaring a field private, you prohibit anybody outside your current class to access the field.

Read about visibility here: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

MaxRumford
  • 175
  • 10
  • *"If you had a private field that no method could access, you could never read or update its value and thus render it unneccessary."* That's not true, accessor and mutator methods exist for this sole purpose. All I'm saying is that methods which do not belong to the calling instance (`static`) should not be able to access the private data. – Priyanshul Govil Feb 15 '21 at 08:24
  • 1
    What do accessor and mutator methods do, if not access the field? I agree, data should be as private as possible. That's why you should always use accessor and mutator methods to manipulate your fields (and thus control the way they are handled). Your private fields actually are safe from outside access, as other methods (from outside the current class) will be able to access the field, not even from subclasses. That's as hidden as your private field can get. – MaxRumford Feb 15 '21 at 08:27
  • 2
    "Private means that the current class (and only the current class) can access the field." This is not true: with `private` and `protected` the whole source file has acces to it. – Usagi Miyamoto Feb 15 '21 at 08:33