简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM