Priyanshul Govil
Priyanshul Govil

Reputation: 589

Why is it that static methods can access private data?

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.

Upvotes: 1

Views: 115

Answers (1)

MaxRumford
MaxRumford

Reputation: 195

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

Upvotes: 3

Related Questions