简体   繁体   中英

Why is the access to a private field not forbidden?

For my study in the university I'm forced to do some ugly java basics, like working without encapsulation, main method in the same class etc. (I do not want to open a discussion on a java styleguide, I just want to clarify, that I would not write something like this outside of the university)

I've stumbled across a behaviour that I can't explain to my self:

public class Person {
  // fields
  private int age;

  public static void main(String[] args) {
    Person foo1 = new Person();
    foo1.age = 40;
    System.out.println(foo1.age);
  }
}

Why does this piece of code compile and run without error? How is it possible that I can access the private field? Strange behaviour due to having the main Method in the same class?

Because the static method main is a member of class Person and can thus access any private fields or methods in Person .

What are you worried about? That someone will write a class and then be able to access those methods from their own class?

If you're going to be concerned about anything, be concerned that you can access private fields in any class using reflection but even that's necessary for a lot of useful things.

Yes—in Java, private is class private not instance private.

Many other languages use instance private, eg Ruby and Smalltalk.

As your main method is in the same class and the instance variable is having private access it is only available to the methods of the same class. there is no access modifier which can restrict the methods of a same class to access its member variable. that is what happening here. if you have your main method in some other class though in the same package it would not have compiled.

You can access private fields from inside their class. That's the point of having them defined per-class.

You can write any other static method in the Person class and access the private variables from that method. Main is just a name. Such is life.

Because your method main(String[] args) is defined inside the class Person . If the method was defined outside the Person class you would not have been able to do that.

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